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:
-
push(e): Places the element passed as the parameter (e) on top of the stack. -
pop(): Returns the top-most element of the stack and removes it. -
top(): Returns the top-most element of the stack without removing it. -
size(): Returns the total number of elements in the stack. -
empty(): Returnstrue, if the stack is empty, andfalseif 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​).
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