C++ std::stack Functions

About This Index
This page is the C++ std::stack Functions index. Each row links to a full guide with syntax, parameters, return value, three examples, and FAQs.
Learn what a stack is on /cpp/stack. Use this page when you need a specific function such as push(), top(), or pop().
std::stack lives in the <stack> header. You call its functions with a dot, such as st.push(5). It is last in, first out: the newest element sits on top. There is no iterator and no []. The 8 functions are listed below with the C++ version each one needs.
How to Call a stack Function
Include <stack>, create a stack, and call the functions on it:
#include <stack>
#include <iostream>
#include <vector>
std::stack<int> st; // LIFO: newest on top
st.push(10); // add on top
st.push(40);
st.emplace(20); // build in place (C++11)
int newest = st.top(); // 20, read (or assign) the top
std::size_t n = st.size(); // 3
bool none = st.empty(); // false
st.pop(); // remove 20, returns nothing
std::vector<int> more = {5, 6};
st.push_range(more); // C++23 only C++ std::stack Functions Table
All function guides in this C++ tutorial series (8 tutorials), grouped by purpose.
Capacity
2 functionsCheck if the stack is empty and how many elements it holds.
Element access
1 functionLook at the one element you can see: the newest one on top (LIFO).
Modifiers
5 functionsAdd elements on top, remove the top element, or swap two stacks.
| Function | Description | Since | Tutorial |
|---|---|---|---|
push() | Add one element on top of the stack. | C++98 | Try it |
push_range() | Add every element of a range on top (needs C++23). | C++23 | Try it |
emplace() | Build a new element on top from constructor arguments. | C++11 | Try it |
pop() | Remove the top element. It does not return the value. | C++98 | Try it |
swap() | Swap the contents of two stacks in one step. | C++11 | Try it |
Frequently Asked Questions
Start with emplace()
Build a new element right inside the stack, the first function in the alphabetical list.
12 people found this page helpful
