How is a Stack Called?
In any program where we want to use a stack or do any operation on a stack in C++, all we need to do is add the header file “#include <stack>” first. We then use the below syntax to define the stack.
Syntax Of Stack In C++
std::stack<T> my_stack;
// or
std::stack<T, container> my_stack (container_instance);
Where:
- T is the data type of elements in the stack like int, or char.
-
container is the data structure used to initialize your stack. This is optional and the stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements.
- container_instance is the instance of container type.
This may appear complicated, but fear not! Next, we'll look at all of the operations that may be performed on a stack in STL, as well as the appropriate code.
C++ Stack Template Parameters
There are two parameters of the Stack template in C++:
-
Type (T): Specifies the type of elements stored in the stack. It can be any valid C++ data type, such as int, float, or custom-defined classes.
-
Container (Container): Specifies the underlying container type used to implement the stack, such as deque, vector, or list. It determines the stack's internal storage and operations' efficiency.
Functions in C++ Stack
1. push()
When we use a container we either insert an element or remove an element from it. The push method allows us to insert elements into our stack. And every time we push an element to our stack it is always added to the top of the stack.
The syntax to the function is :
Stack_Name.push()
Parameters :
The element value which needs to be added is passed
Return Value:
Adds the value mentioned in the function on the top of the stack
Examples :
Input : stack01
stack01.push(7);
Output : 7
Input : stack01
stack01.push(5);
stack01.push(6);
Output : 5 , 6
2. pop()
When we use a container we either insert an element or remove an element from it. Pop method allows us to remove elements from our stack. And every time we pop an element from our stack it is always the top element that gets removed.
The syntax to the function is :
Stack_Name.pop()
Parameters :
No parameter is passed
Return Value:
Removes the top most value of the stack
Examples :
Input : stack01 = 7, 8, 9
stack01.pop();
Output : 7, 8
Input : stack01 = 7, 8, 9, 10, 11
stack01.pop();
Output : 7, 8, 9, 10
Now we have 5 operations that come in handy when we are working on stacks. But how? How can we implement all these operations?
Let’s understand now!
3. empty()
As stacks are containers they either can have some elements in them or can be totally empty. This empty() function can be used to find the same.
The syntax to the empty function is :
Stack_Name.empty()
Parameters :
There are no parameters Passed.
Return Value:
True, If our stack is empty.
False, If our stack is not empty.
Examples :
Input : stack01
stack01.empty();
Output : True
Input : stack01 = 7,19,21;
stack01.empty();
Output : False
4. size()
The second operation or function that we can perform on a stack is the size(). This function returns the size of our stack or the count of the elements that are present in our container.
The syntax to the function is :
Stack_Name.size()
Parameters :
There are no parameters Passed.
Return Value:
Number of elements present in the container
Examples :
Input : stack01 = 7,8,9
stack01.size();
Output : 3
Input : stack01 = 10,11,12,13,14,15
stack01.size();
Output : 6
5. top()
As stack follows last in first out order of elements, the last element i.e the newest element always stays on the top of the stack.
To return that element(newly added) we use this top() function.
The syntax to our top function comes as follows:
Stack_Name.top()
Parameters :
There are no parameters Passed.
Return Value :
Element that is on the top of the stack
Examples :
Input : stack01.push(1);
stack01.push(2);
stackname.top();
Output : 2
Input : stack01.push(7);
stack01.push(9);
stack01.push(4);
stack01.top();
Output : 4
Implementation of Stack in C++ using STL
C++
// C++ program to implement
// push(), pop(), top(), empty(), size() operations
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> stack01;
stack01.push(7);
stack01.push(8);
stack01.push(9);
stack01.push(10);
// Stack becomes 7, 8, 9, 10
stack01.pop();
stack01.pop();
// Stack becomes 7, 8
if(stack01.empty()){
cout << "true"<<endl;
//our stack isn't empty so we'll not get true
}
else{
cout << "False" << endl;
//our stack isn't empty so we'll get false
}
cout << stack01.top() << endl;
//we have 8 as output as 8 is on the top
cout << stack01.size() << endl;
//we will get 2 as the size as we have 7 and 8 in our stack
}

You can also try this code with Online C++ Compiler
Run Code
Output -
False
8
2
You can also compile this code with the help of Online C++ Compiler
Explanation
Let’s see why this code works now!
- We use the usual header file and an extra header file “#include <stack>”.
- Using namespace std; makes it easier to use the classes without calling them.
- Making a main() function states that the entire logic of the code will be coded inside this function.
- Creating an integer stack makes us eligible to store integer values in the container.
- Use push() to add elements in the stack -
- Add 7 to the stack
- Add 8 to the stack
- Add 9 to the stack
- Add 10 to the stack
- Pop() one element from the stack. 10 gets removed from the stack.
- Pop one more element from the stack. 9 gets removed from the stack.
- Using empty() we check if the stack is empty or not (we get false because our stack is not empty).
- Use a top() function to return the topmost element of our stack. (Our topmost element is 8).
- Size() is used to return the size of our stack. We get 2 as our stack has only 2 elements left.
- End the main function.
Complexity Analysis
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(ele) – Adds the element ‘ele’ at the top of the stack – Time Complexity: O(1)
pop()– Deletes the top most element of the stack – Time Complexity: O(1)
Must Read Stack Operations
Applications Of Stack in C++
1. Expression Evaluation: Stacks are used to evaluate arithmetic expressions, postfix expressions, and infix-to-postfix conversion.
C++
#include <iostream>
#include <stack>
#include <string>
int evaluatePostfix(const std::string& expression) {
std::stack<int> stack;
for (char c : expression) {
if (isdigit(c))
stack.push(c - '0');
else {
int operand2 = stack.top(); stack.pop();
int operand1 = stack.top(); stack.pop();
switch (c) {
case '+': stack.push(operand1 + operand2); break;
case '-': stack.push(operand1 - operand2); break;
case '*': stack.push(operand1 * operand2); break;
case '/': stack.push(operand1 / operand2); break;
}
}
}
return stack.top();
}
int main() {
std::string postfixExpression = "53+2*";
std::cout << "Postfix expression result: " << evaluatePostfix(postfixExpression) << std::endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
Postfix expression result: 16
2. Function Call Stack: Stack is used by compilers to manage function calls, storing return addresses, local variables, and other relevant data during recursive or nested function calls.
3. Undo Mechanism: Stacks are used in text editors, drawing programs, and other applications to implement undo functionality, storing previous states or actions that can be reverted.
4. Balanced Parentheses Checking: Stacks are used to check the balance of parentheses, braces, and brackets in expressions or code blocks.
5. Backtracking Algorithms: Stacks are utilized in backtracking algorithms like depth-first search (DFS), where they store the state of visited nodes or paths to backtrack when necessary.
6. Expression Parsing: Stacks are used in parsing algorithms to handle nested structures like XML, HTML, and JSON, managing the hierarchy of opening and closing tags or brackets.
Frequently Asked Questions
What is a stack in CPP?
A stack in C++ is a container adaptor that allows only push, pop, and top operations, following the Last In First Out (LIFO) principle.
Is stack a function in C++?
No, stack is not a function in C++. It is a container adaptor provided by the Standard Template Library (STL).
What is a stack variable in C++?
A stack variable in C++ is a local variable stored in the stack memory region, which has automatic storage duration and is deallocated when out of scope.
Conclusion
This article has cleared most of the doubts about the stack in C++( using STL) and the functions that are used on the stack as well.
Don’t know if STL is a good thing to learn.
Simple Answer - Yes!
As you start solving advanced data structure problems you will end up using containers and algorithms which are already present in STL just like stack and it becomes easy to solve the problems then.
If you want to solve some problems on the stack like the minimum stack problem and sharpen your skills you can refer to Code360.
Recommended Reading
Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc.
You can also consider our Mern Stack Course to give your career an edge over others.