In C++11, emplace() adds a new element to a std::stack by building it on top. You pass the constructor arguments, not a finished object, and the stack creates the element itself.
This is handy for pairs, tuples, and structs. Instead of st.push(std::make_pair(3, "low")) you write st.emplace(3, "low"). The new element becomes the top, just like push().
This function is a member function of std::stack<T>, declared in the <stack> header. It needs C++11 or newer (-std=c++11). You call it with a dot, for example st.emplace(...).
Syntax
Give emplace() the arguments for the constructor of the element type. It needs C++11 or newer.
Builds a new element from args on top of the stack.
emplace() returns nothing. The arguments must match a constructor of the element type. For simple types such as int, push() and emplace() behave the same.
Library declarations
C++
template<class... Args>
void emplace(Args&&... args); // C++11
// stack<T, Container> from <stack>
// It calls c.emplace_back(std::forward<Args>(args)...).
Parameters
Parameter
Description
args...
Zero or more arguments that are passed to the constructor of the element type T. The stack builds the new top element from them.
Return Value
Return Value
Description
Nothing
emplace() returns void.
C++ Examples
Example 1 — Emplace Pairs Without make_pair
Pass both values straight to emplace(). The newest pair sits on top.
using Step = ... gives the pair a short name. Each emplace() builds one step on top.
The newest step is number 3. That is the first one the loop undoes.
Popping continues until the stack is empty. The steps come out newest first, which matches undo behavior.
Frequently Asked Questions
It builds a new element on top of the stack from constructor arguments. The new element becomes the top.
push() takes a finished object. emplace() takes the constructor arguments and builds the object in place, which can save a copy or a move. For plain numbers they behave the same.
emplace() was added in C++11. Every modern compiler supports it. Compile with -std=c++11 or newer.
No. For stack it returns void. You read the top element later with top().
No. A stack is LIFO. The newest emplaced element is always on top, regardless of its value.