In C++, push() adds one new element on top of a std::stack. The new value becomes the top immediately. Older values stay below it until you pop().
The order you push in matters. Push 10, then 50, then 20, and top() gives 20 first. That is last in, first out (LIFO). A queue would serve 10 first instead, and a priority_queue would serve the largest first.
This function is a member function of std::stack<T>, declared in the <stack> header. It has been available since the first C++ standard, so every compiler supports it. You call it with a dot, for example st.push(...).
Syntax
Call push() with the value you want to add. Two overloads exist: one copies the value, the other moves it.
C++
std::stack<int> st;
st.push(10);
st.push(50); // 50 becomes the top
st.push(20); // 20 becomes the top
int newest = st.top(); // 20
Call
What it does
st.push(value)
Copies value onto the top of the stack.
st.push(std::move(value))
Moves value onto the top. It is faster for big objects such as long strings.
push() returns nothing, so you cannot use the result. Each call is typically constant time for the default deque backing. If you want to build the object right inside the stack, see emplace().
Library declarations
C++
void push(const value_type& value);
void push(value_type&& value); // C++11
// stack<T, Container> from <stack>
// It calls c.push_back(value) on the underlying container.
Parameters
Parameter
Description
value
Required. The element to add. It must have the type T of the stack, or be convertible to it. It becomes the new top.
Return Value
Return Value
Description
Nothing
push() returns void. The stack is changed in place, and its size grows by one.
C++ Examples
Example 1 — Push Numbers in Order
Push three numbers and then read them back. They come out in reverse order.
Last edit: delete B
After undo: type B
Edits left: 2
How It Works
Three edits are pushed. The newest edit, "delete B", sits on top.
pop() removes that last edit. The previous edit, "type B", becomes the new top.
Two edits remain. This is the classic undo pattern: push to record, pop to undo.
Frequently Asked Questions
It adds one element on top of the stack. That new element becomes the value returned by top().
No. For a stack, push() always places the element on top. A queue adds at the back and removes from the front.
With the default deque backing, push() is typically O(1). If you use a vector as the underlying container, occasional reallocations can make a push slower.
push() takes a ready-made object. emplace() takes constructor arguments and builds the object inside the stack, which can avoid an extra copy. Both place the new element on top.
No. A stack only supports operations at the top. To change lower elements you must pop until you reach them.