C plus plus programming
June 3, 2026 2 min read

Stack in c plus plus programming with basic methods

HS
HEMANT SINGH
Technical Writer & Educator

The std::stack is a container adapter in C++ STL that provides a Last-In-First-Out (LIFO) data structure. It supports several useful methods to manage elements on the top of the stack. Below, we explain each key method with a definition and example code snippet.

🔧 Stack Methods Explained

1. push(val)

Definition: Adds the element val to the top of the stack.

stack<int> s;
s.push(10);  // Stack now contains: {10}
s.push(20);  // Stack now contains: {10, 20}

2. pop()

Definition: Removes the top element from the stack. Note: It does not return the removed element.

s.pop();  // Removes the top element (20), stack now: {10}

3. top()

Definition: Returns a reference to the top element of the stack without removing it.

int topElement = s.top();  // Returns 10

4. empty()

Definition: Returns true if the stack is empty, otherwise false.

bool isEmpty = s.empty();  // false if stack contains elements

5. size()

Definition: Returns the number of elements currently stored in the stack.

int stackSize = s.size();  // Returns the number of elements

In this category