Introduction to Stack STL, DSA in C++

By Shakib Ansari | Date: Fri, Jul 11, 2025

What is Stack STL

C++ mein stack ko use karne ke liye ham Stack STL ka use karte hai. Ye hame stack ke readymade functions provide karta hai, isme hame stack ki internal implementation janne ki zarurat nhi padhti hai.

Note: Stack par ek article already published hai agar aapko ye samjhna hai what is stack, advantages, disadvantages, application and implementation using array and linked list, you can go to this article.

Syntax to Include Stack in C++

#include <stack>
using namespace std;

STL ki stack class C++ ke <stack> header me hoti hai.

Basic Stack Operations in STL

  1. Push: s.push(x); Stack me element insert karna.
  2. Pop: s.pop(); Top element ko remove karna.
  3. Top: s.top(); Stack ka top element dekhna.
  4. Empty: s.empty(); Stack empty hai ya nahi (true/false)
  5. Size: s.size(); Stack me kitne elements hain, ye size dena.

Stack Operations using C++ STL Code

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

int main() {
    stack<int> s;

    s.push(10);
    s.push(20);
    s.push(30);

    cout << "Top element: " << s.top() << endl; // 30

    s.pop();

    cout << "Top after pop: " << s.top() << endl; // 20
    cout << "Size: " << s.size() << endl;         // 2
    cout << "Is empty: " << s.empty() << endl;    // 0 (false)

    return 0;
}

Stack Visualization

Stack s;

s.push(10);  // bottom
s.push(20);
s.push(30);  // top

After pop(), stack becomes:

s: [10, 20]
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments