Loading lessons...
Stacks (std::stack)
Stacks (std::stack)
Picture a stack of plates: you place plates on top, and the top plate comes off first. That rule is LIFO - Last In, First Out.
Create a stack
#include <stack>
std::stack<int> plates;
Push, peek, pop
plates.push(1); // 1 goes on the top
plates.push(2); // top is now 2
std::cout << plates.top(); // reads 2 without removing
plates.pop(); // removes the top (2)
push(x)puts x on the top.top()reads the top element and leaves it in place.pop()removes the top element and does not return it.
Because pop returns nothing, read top() first if you need the value.
Empty and size
if (plates.empty()) {
// no elements left
}
std::cout << plates.size(); // the count on the stack
Empty the stack safely
while (!plates.empty()) {
std::cout << plates.top() << "\n";
plates.pop();
}
Checks the top for printing, then pops, until the stack is empty.
TL;DR
- A stack follows LIFO (last in, first out).
push(x)adds,pop()removes the top,top()reads it.pop()returns nothing, so readtop()first when you need the value.empty()andsize()report what is left.- Pair
top()withpop()inside a loop to drain a stack.