In C++, pop()removes the top element of a std::stack. That is the newest element, the one top() would return. After the call, the previous element becomes the new top.
The important thing to remember is that pop()does not return the removed value. Its return type is void. If you need the value, read it with top() first, and then call pop().
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.pop(...).
Syntax
Call pop() with empty brackets. First read the value with top() if you need it.
C++
std::stack<int> st;
st.push(5);
st.push(30);
st.push(10);
int value = st.top(); // read 10 first
st.pop(); // then remove it
// the new top is 30
Call
What it does
st.pop()
Removes the top element. Returns nothing.
To take an element out, call top() first and then pop(). A stack has no way to remove an element from the middle, only the top one.
Library declarations
C++
void pop();
// stack<T, Container> from <stack>
// It calls c.pop_back() on the underlying container.
Parameters
Parameter
Description
None
pop() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
pop() returns void. It does not give back the removed element.
Undefined behavior
If the stack is empty, there is nothing to remove. Check empty() first.
C++ Examples
Example 1 — Read with top(), Then pop()
Save the top value, remove it, and look at the new top.