0
0
CppHow-ToBeginner · 3 min read

How to Use Stack in C++: Syntax and Examples

In C++, you use the stack container from the <stack> header to store elements in a last-in, first-out (LIFO) order. You can add elements with push(), remove with pop(), and access the top element with top().
📐

Syntax

The stack is a container adapter that works on top of other containers like vector or deque. Here is the basic syntax:

  • std::stack<Type> stackName; - declares a stack of elements of type Type.
  • push(value) - adds value to the top of the stack.
  • pop() - removes the top element.
  • top() - returns the top element without removing it.
  • empty() - checks if the stack is empty.
  • size() - returns the number of elements.
cpp
std::stack<Type> stackName;
stackName.push(value);
stackName.pop();
Type topValue = stackName.top();
bool isEmpty = stackName.empty();
size_t count = stackName.size();
💻

Example

This example shows how to create a stack of integers, add elements, access the top, and remove elements until the stack is empty.

cpp
#include <iostream>
#include <stack>

int main() {
    std::stack<int> numbers;

    // Add elements
    numbers.push(10);
    numbers.push(20);
    numbers.push(30);

    // Access and remove elements
    while (!numbers.empty()) {
        std::cout << "Top element: " << numbers.top() << std::endl;
        numbers.pop();
    }

    return 0;
}
Output
Top element: 30 Top element: 20 Top element: 10
⚠️

Common Pitfalls

Common mistakes when using stack include:

  • Calling top() or pop() on an empty stack causes undefined behavior (usually a crash).
  • Forgetting that pop() does not return the removed element; you must call top() before pop() to access it.
  • Assuming stack supports iteration — it does not because it is a container adapter.
cpp
/* Wrong way: calling top() on empty stack */
#include <stack>
#include <iostream>

int main() {
    std::stack<int> s;
    // std::cout << s.top(); // ERROR: stack is empty
    if (!s.empty()) {
        std::cout << s.top(); // Safe way
    }
    return 0;
}
📊

Quick Reference

Remember these key functions for std::stack:

FunctionDescription
push(value)Add element to the top
pop()Remove top element
top()Access top element
empty()Check if stack is empty
size()Get number of elements

Key Takeaways

Use push() to add and pop() to remove elements from the stack.
Always check empty() before calling top() or pop() to avoid errors.
stack follows last-in, first-out (LIFO) order.
pop() does not return the removed element; use top() first to access it.
stack does not support iteration like other containers.