C++ stack

Beginner
8 min read
Updated: Nov 2026
3 examples
<stack>

Definition and Usage

In C++, std::stack<T> is a container adaptor from the <stack> header that keeps the newest element on top. You add with push() or emplace(), peek with top(), and remove with pop(). That order is called last in, first out (LIFO).

A stack is usually backed by a std::deque. You do not need to manage that yourself. The daily pattern is simple: push() to add, top() to read the top, and pop() to remove it. Use empty() before you read or remove.

This page teaches what a stack is. The stack Functions index lists every function guide in this series.

You can only see the top.

A stack has no [], no at(), and no begin() or end(). You cannot loop over all elements with iterators. Reading or removing from an empty stack with top() or pop() is undefined behavior, so check empty() first. Unlike priority_queue, a non-const top() returns a reference you can assign through.

C++ Syntax

Common ways to create and use a std::stack:

C++
#include <deque>
#include <iostream>
#include <stack>
#include <vector>

std::stack<int> st;                              // default: backed by deque
std::stack<int, std::vector<int>> stVec;       // optional: backed by vector

st.push(10);
st.push(40);
st.emplace(20);                  // C++11

int newest = st.top();           // 20
st.top() = 25;                   // assign through the reference
st.pop();                        // removes 25, returns nothing
std::size_t n = st.size();       // 2
bool none = st.empty();          // false

The LIFO Pattern

Think of a stack of plates. You only touch the top plate:

ActionFunctionWhat happens
Add on toppush() / emplace()The new element becomes the top
Peek at toptop()Returns a reference; the element stays
Remove toppop()Removes the top; returns nothing
Safe checkempty() / size()Know if top() / pop() are allowed
Typical usesUndo history, matching brackets, depth-first search, expression evaluation

stack vs queue vs priority_queue

All three are container adaptors. They share push(), pop(), size(), and empty(). The difference is which element comes out next:

Featurestd::stackstd::queuestd::priority_queue
Order outNewest first (LIFO)Oldest first (FIFO)Highest priority first
Read the next itemtop()front() (and back())top() (const)
Header<stack><queue><queue>
Default backingdequedequevector (heap)
Use it forUndo, DFS, bracketsWaiting lines, BFSScheduling, top K, Dijkstra

Pick the function by the job you want to do:

FunctionUse it when you want to…
push() / emplace()Add one element on top. Use emplace() to build a pair or struct right inside the stack
push_range()Add a whole vector or array at once (needs C++23)
top() / pop()Read the top element, then remove it. pop() returns nothing — read with top() first
empty() / size()Check that the stack has elements before top() or pop(), or count them
swap()Exchange two stacks of the same type, or empty a stack

C++ Examples

Three short programs that show how a std::stack works.

Example 1 — Push, Top and Pop

A first program: push four numbers, read the top, and pop them all out in reverse order.

C++
#include <iostream>
#include <stack>

int main() {
    std::stack<int> st;
    st.push(20);
    st.push(5);
    st.push(30);
    st.push(10);

    std::cout << "size: " << st.size() << '\n';
    std::cout << "top: " << st.top() << '\n';

    std::cout << "order:";
    while (!st.empty()) {
        std::cout << ' ' << st.top();
        st.pop();
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. Four push() calls add 20, 5, 30, 10. Each new value sits on top of the older ones.
  2. size() counts 4 elements. top() shows 10, the last value pushed, and leaves it in the stack.
  3. The loop uses top() to read and pop() to remove, until empty() is true. The numbers come out in reverse push order: last in, first out.

Example 2 — LIFO Undo Stack

A stack is perfect for undo. Push each change, then pop to go back one step.

C++
#include <iostream>
#include <stack>
#include <string>

int main() {
    std::stack<std::string> undo;
    undo.push("open file");
    undo.push("type hello");
    undo.push("save");

    std::cout << "Last action: " << undo.top() << '\n';
    undo.pop();
    std::cout << "Undo -> now: " << undo.top() << '\n';
    undo.pop();
    std::cout << "Undo -> now: " << undo.top() << '\n';
    return 0;
}

How It Works

  1. Three actions are pushed in order. The newest action, "save", sits on top.
  2. The first pop() removes "save". The next top is "type hello".
  3. Another pop() reveals "open file". This is last in, first out (LIFO).

Example 3 — stack vs queue

A stack is LIFO (newest first). A queue is FIFO (oldest first). Same three numbers leave in different orders.

C++
#include <iostream>
#include <queue>
#include <stack>

int main() {
    std::stack<int> st;
    std::queue<int> q;

    int values[] = {3, 9, 1};
    for (int v : values) {
        st.push(v);
        q.push(v);
    }

    std::cout << "stack order: ";
    while (!st.empty()) {
        std::cout << st.top() << ' ';
        st.pop();
    }
    std::cout << '\n';

    std::cout << "queue order: ";
    while (!q.empty()) {
        std::cout << q.front() << ' ';
        q.pop();
    }
    std::cout << '\n';
    return 0;
}

How It Works

  1. Both containers receive 3, 9, 1 in the same order. Both use push(), pop(), and empty().
  2. std::stack is last in, first out (LIFO). It reads with top() and gives the newest first: 1 9 3.
  3. std::queue is first in, first out (FIFO). It reads with front() and gives the numbers back as they arrived: 3 9 1. A priority_queue would instead keep the largest on top.

Next: C++ stack Functions Index

After you know what a stack is for, open the function index for a full tutorial on each function.

Start withWhy
push()Add elements on top, the first thing every stack needs
top()Read (or assign) the top element without removing it
pop()Remove the top element (remember: it returns nothing)
emplace()Build pairs and structs right inside the stack

Full list: C++ std::stack Functions index (/cpp/stack/function).

Frequently Asked Questions

std::stack is a container adaptor from the <stack> header. It is last in, first out (LIFO): you push and emplace on top, read with top(), and remove with pop(). It is usually backed by a deque.
stack is LIFO (newest first) and reads with top(). queue is FIFO (oldest first) and reads with front(). priority_queue is a max-heap by default and also reads with top(), but the top is the highest priority, not the newest.
No. pop() returns void. Read the value with top() first, then call pop(). Calling top() or pop() on an empty stack is undefined behavior.
Yes, on a non-const stack. top() returns a reference, so you can assign through it (for example st.top() = 99). Prefer that only when you mean to edit the top element in place.
Open the C++ std::stack Functions index. It lists all 8 member functions with a short description, the C++ version needed, and a full tutorial for each.

Browse every stack function

Open the functions index for categorized guides with examples and FAQs.

Stack Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful