C++ Stacks


stack in C++ is a special type of container that follows the Last In, First Out (LIFO) principle. This means the last element added to the stack is the first one to be removed. You can think of it like a stack of books: you can only add or remove the top book, not the ones in the middle or bottom.

The stack container in C++ is part of the Standard Template Library (STL) and is defined in the <stack> header. It is typically built on top of other containers like vectors, deques, or lists, and provides restricted access — only the top element can be accessed or modified directly.

Why Use a Stack in C++

Stacks are useful in situations where data needs to be processed in reverse order of arrival. Some common use cases include:

  • Undo/Redo functionality in applications.

  • Expression evaluation (like postfix or prefix evaluation).

  • Balancing parentheses in compilers.

  • Function call management (handled internally by recursion).

Stacks ensure controlled data management, making them ideal for temporary storage of elements.

Declaring a Stack

To create a stack in C++, include the <stack> header file and use the std::stack class template.

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> numbers;
    numbers.push(10);
    numbers.push(20);
    numbers.push(30);

    cout << "Top element: " << numbers.top() << endl;
    return 0;
}

Explanation:
Here, we declared a stack of integers named numbers. We added three elements using push() and accessed the top element using top().

Common Stack Operations in C++

The C++ stack provides several important member functions to manipulate elements.

1. push()

Adds an element to the top of the stack.

numbers.push(50);

2. pop()

Removes the topmost element from the stack.

numbers.pop();

3. top()

Returns a reference to the top element.

cout << numbers.top();

4. empty()

Checks whether the stack is empty. Returns true if no elements exist.

if (numbers.empty()) cout << "Stack is empty";

5. size()

Returns the total number of elements in the stack.

cout << "Size: " << numbers.size();

Example: Basic Stack Operations

Here’s a complete example demonstrating push, pop, and top operations.

#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> nums;
    nums.push(10);
    nums.push(20);
    nums.push(30);

    cout << "Top element: " << nums.top() << endl;
    nums.pop();
    cout << "Top after pop: " << nums.top() << endl;
    cout << "Size of stack: " << nums.size() << endl;

    return 0;
}

Output:

Top element: 30
Top after pop: 20
Size of stack: 2

Accessing Elements in a Stack

Stacks do not support iteration or random access like vectors or lists. You can only access the top element at any time. If you need to access all elements, you must pop them one by one.

Example:

while (!nums.empty()) {
    cout << nums.top() << " ";
    nums.pop();
}

Stack Implementation Using Different Containers

By default, a stack uses a deque as its underlying container. However, you can also specify other containers such as vector or list.

stack<int, vector<int>> vectorStack;
stack<int, list<int>> listStack;

This flexibility allows you to choose the best container depending on your program’s requirements.

Real-Life Example: Reversing a String Using Stack

#include <iostream>
#include <stack>
using namespace std;

int main() {
    string text = "hello";
    stack<char> st;

    for (char ch : text)
        st.push(ch);

    cout << "Reversed: ";
    while (!st.empty()) {
        cout << st.top();
        st.pop();
    }
    return 0;
}

Output:

Reversed: olleh

Explanation:
Each character of the string is pushed into the stack. Since stacks follow LIFO order, popping elements reverses the string.

Advantages of Using Stacks

  • Simple to implement and use.

  • Automatically manages order (LIFO).

  • Efficient for temporary data storage.

  • Useful for recursion, expression evaluation, and undo operations.

Limitations of Stacks

  • Only the top element is directly accessible.

  • Not suitable for random access or traversal.

  • Requires additional storage space when nested deeply.

When to Use a Stack

Use a stack when:

  • You need to process elements in reverse order.

  • You want to implement recursion or expression evaluation.

  • You need to manage states like undo or backtracking operations.

Summary of the Tutorial

A C++ Stack is an STL container that provides a simple yet powerful way to store data using the LIFO order. It’s ideal for situations where the most recently added element needs to be processed first. With efficient operations like push(), pop(), and top(), stacks play a vital role in solving many algorithmic and system-level problems in C++ programming.


Practice Questions

  1. Write a C++ program to create a stack of integers and perform basic operations like push, pop, and top.

  2. Create a program that takes a string as input and uses a stack to reverse it.

  3. Write a C++ program to check whether a given string of parentheses is balanced using a stack.

  4. Build a program that converts a decimal number to binary using a stack.

  5. Write a program to display all elements of a stack without modifying its original order.

  6. Create a program that removes all elements from a stack and checks if it’s empty.

  7. Write a program to count the number of elements currently present in a stack.

  8. Build a program to find the largest and smallest element in a stack of integers.

  9. Write a C++ program to copy all elements from one stack to another in the same order.

  10. Create a program that simulates a browser’s back button feature using a stack.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top