codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

67 / 87 topics
62Introduction to STL & Containers63std::array64Vectors65List & Forward List66Deque67Stack68Queue & Priority Queue69Map & Multimap70Set & Multiset71Unordered Map & Unordered Multimap72Unordered Set & Unordered Multiset73Iterators74Algorithms75Functors
Tutorials/C++ Programming/Stack
⚡C++ Programming

Stack

Updated 2026-05-12
30 min read

Stack

In this tutorial, we will delve into the Stack data structure using the Standard Template Library (STL) in C++. A stack is a fundamental linear data structure that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are widely used in various applications, including expression evaluation, function call management, and undo mechanisms.

Introduction

A stack is a linear data structure where elements are added or removed from only one end, known as the top. This makes stacks ideal for scenarios where you need to process items in the reverse order of their arrival. The primary operations associated with a stack are:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the top element from the stack.
  • Top: Retrieves the top element without removing it.
  • Empty: Checks if the stack is empty.
  • Size: Returns the number of elements in the stack.

Understanding these operations and their implementations will help you effectively use stacks in your C++ programs. Let's explore each operation with code examples.

Core Content

1. Push Operation

The push operation adds an element to the top of the stack. Here’s how you can implement it using the STL stack container:

stack_push.cpp
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 myStack.push(10);
7 myStack.push(20);
8 myStack.push(30);
9
10 while (!myStack.empty()) {
11 std::cout << "Top element: " << myStack.top() << std::endl;
12 myStack.pop();
13 }
14
15 return 0;
16}
Output
Top element: 30
Top element: 20
Top element: 10

2. Pop Operation

The pop operation removes the top element from the stack. In the previous example, we used a loop to pop all elements until the stack is empty.

stack_pop.cpp
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 myStack.push(10);
7 myStack.push(20);
8 myStack.push(30);
9
10 while (!myStack.empty()) {
11 std::cout << "Popped element: " << myStack.top() << std::endl;
12 myStack.pop();
13 }
14
15 return 0;
16}
Output
Popped element: 30
Popped element: 20
Popped element: 10

3. Top Operation

The top operation retrieves the top element without removing it from the stack.

stack_top.cpp
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 myStack.push(10);
7 myStack.push(20);
8 myStack.push(30);
9
10 std::cout << "Top element: " << myStack.top() << std::endl;
11
12 return 0;
13}
Output
Top element: 30

4. Empty Operation

The empty operation checks if the stack is empty.

stack_empty.cpp
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 std::cout << "Is stack empty? " << (myStack.empty() ? "Yes" : "No") << std::endl;
7
8 myStack.push(10);
9 std::cout << "After pushing an element, is stack empty? " << (myStack.empty() ? "Yes" : "No") << std::endl;
10
11 return 0;
12}
Output
Is stack empty? Yes
After pushing an element, is stack empty? No

5. Size Operation

The size operation returns the number of elements in the stack.

stack_size.cpp
1#include <iostream>
2#include <stack>
3
4int main() {
5 std::stack<int> myStack;
6 std::cout << "Size of stack: " << myStack.size() << std::endl;
7
8 myStack.push(10);
9 myStack.push(20);
10 std::cout << "After pushing two elements, size of stack: " << myStack.size() << std::endl;
11
12 return 0;
13}
Output
Size of stack: 0
After pushing two elements, size of stack: 2

Stack Applications

1. Bracket Matching

One common application of stacks is bracket matching in expressions. You can use a stack to ensure that every opening bracket has a corresponding closing bracket.

stack_bracket_matching.cpp
1#include <iostream>
2#include <stack>
3#include <string>
4
5bool areBracketsBalanced(const std::string& expression) {
6 std::stack<char> bracketStack;
7 for (char ch : expression) {
8 if (ch == '(' || ch == '{' || ch == '[') {
9 bracketStack.push(ch);
10 } else if (ch == ')' || ch == '}' || ch == ']') {
11 if (bracketStack.empty()) {
12 return false;
13 }
14 char top = bracketStack.top();
15 bracketStack.pop();
16 if ((ch == ')' && top != '(') ||
17 (ch == '}' && top != '{') ||
18 (ch == ']' && top != '[')) {
19 return false;
20 }
21 }
22 }
23 return bracketStack.empty();
24}
25
26int main() {
27 std::string expression = "{[()]}";
28 if (areBracketsBalanced(expression)) {
29 std::cout << "Brackets are balanced." << std::endl;
30 } else {
31 std::cout << "Brackets are not balanced." << std::endl;
32 }
33
34 return 0;
35}
Output
Brackets are balanced.

2. Undo Mechanism

Stacks can be used to implement an undo mechanism in applications like text editors or painting software.

stack_undo.cpp
1#include <iostream>
2#include <stack>
3#include <string>
4
5class TextEditor {
6private:
7 std::stack<std::string> history;
8 std::string currentText;
9
10public:
11 void type(const std::string& text) {
12 history.push(currentText);
13 currentText += text;
14 }
15
16 void undo() {
17 if (!history.empty()) {
18 currentText = history.top();
19 history.pop();
20 }
21 }
22
23 std::string getCurrentText() const {
24 return currentText;
25 }
26};
27
28int main() {
29 TextEditor editor;
30 editor.type("Hello");
31 editor.type(", World!");
32 std::cout << "Current text: " << editor.getCurrentText() << std::endl;
33
34 editor.undo();
35 std::cout << "After undo: " << editor.getCurrentText() << std::endl;
36
37 return 0;
38}
Output
Current text: Hello, World!
After undo: Hello

Summary

OperationDescription
pushAdds an element to the top of the stack.
popRemoves the top element from the stack.
topRetrieves the top element without removing it.
emptyChecks if the stack is empty.
sizeReturns the number of elements in the stack.

Key takeaways:

  • Stacks follow the LIFO (Last-In-First-Out) principle.
  • Use stacks for applications like bracket matching and undo mechanisms.
  • The STL provides a convenient stack container that simplifies stack operations.

What's Next?

In the next tutorial, we will explore another fundamental data structure: Queue. Queues differ from stacks in their operation order (FIFO vs LIFO) and have various applications such as scheduling tasks and breadth-first search algorithms. Stay tuned!


PreviousDequeNext Queue & Priority Queue

Recommended Gear

DequeQueue & Priority Queue