How to use the STL stack in C++

The Standard Template Library (STL) in C++ contains the implementation of commonly known data structures such as arrays, lists, stacks, etc.

To use the STL stack, you must first include the stack file:

#include <stack>

Next, declare an object of type stack and specify the type of elements it will contain using the C++ template syntax.

STL provides the following methods that are​ (usually) associated with a stack:

  1. push(e): Places the element passed as the parameter (e) on top of the stack.

  2. pop(): Returns the top-most element of the stack and removes it.

  3. top(): Returns the top-most element of the stack without removing it.

  4. size(): Returns the total number of elements in the stack.

  5. empty(): Returns true, if the stack is empty, and false if otherwise.

Demo

A stack follows the last-in-first-out (LIFO) principle (i.e., the last element added to the stack is the first to be removed​).

1 of 13

Code

#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> s;
// Push elements on the stack:
s.push(3);
s.push(5);
s.push(7);
// Empty the whole stack:
while(!s.empty()){
// Print info:
cout << "top() -> " << s.top() << endl
<< "size() -> " << s.size() << endl << endl;
// Pop out the top element:
s.pop(); // Can be stored in a variable
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved