The container stack

The characteristics of the container stack

The particularity of a container of type stack is that we can only add elements at its end and we can only access/remove its last element. That kind of container is said to be of type LIFO (Last-In Last-Out).

A stack is often visualized as a stack of plates. We can only add a new plate at the top of the stack and we can only remove the one at the top (At least, with only one hand).

Like the other containers, the class std::stack takes, in template argument, the type of the objects (or primitives) it holds.

Its methods

Here is a table with the methods of the container std::stack<T>:

MethodDescription
bool empty() constReturns true only if the stack is empty.
size_type size() constReturns the number of elements inside the stack.
T & top()<br>const T & top() constReturns a reference to the element at the top of the stack.
void push(const T & elem)<br>void push(T && elem) // C++11Adds an element at the top of the stack.
void emplace(Args &&... args) // C++11Constructs a new object at the top of the stack.
void pop()Removes the element at the top of the stack.
void swap(stack & s) // C++11Swaps the content of the two stacks.

Iterators

Because only the last element of a stack can be accessed (We can not iterate through a stack), iterators are useless with containers of type stack.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stack> #include <iostream> int main() { std::stack<int> stack; // Inserts 10 numbers on the stack. for(unsigned c = 0; c < 10; c++) stack.push(c); std::cout << "The content of the stack of " << stack.size() << " elements:\n"; // As long as the stack is not empty. while(!stack.empty()) { // Prints the value of the last element of the stack. std::cout << stack.top() << ' '; // Takes off the last element of the stack. stack.pop(); } std::cout << '\n'; return 0; }