Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
stack empty() and stack size() in C++ STL
Next article icon

Stack in C++ STL

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally called the top of the stack.

Example:

C++
#include <iostream> #include <stack> using namespace std;  int main() {     stack<int> st;      // Pushing elements onto the stack     st.push(1);     st.push(2);     st.push(3);      while(!st.empty()) {         cout << st.top() << " ";         st.pop();     }     return 0; } 

Output
3 2 1 

Explanation: In the above program, we created a stack of integers s. The element 1, 2 and 3 are then pushed one after other into the stack. Due to LIFO order, the elements are stored in the stack in the reverse order as they are inserted.

Syntax

Stack is defined as std::stack class template inside the <stack> header file.

stack<T> st;

where,

  • T: Type of elements in the stack.
  • st: Name assigned to the stack.

Declaration and Initialization

In C++, stack can be declared and initialized in two ways as shown in the below example:

C++
#include <bits/stdc++.h> using namespace std;  void print(stack<int> st) {     while (!st.empty()) {         cout << st.top() << " ";         st.pop();     } }  int main() {          // Declare empty stack     stack<int> st1;          // Insert elements into stack     st1.push(10);     st1.push(20);     st1.push(30);     st1.push(40);          // Create another stack from st1     stack<int> st2(st1);          print(st1);     cout << endl;     print(st2);     return 0; } 

Output
40 30 20 10  40 30 20 10 

Explanation: In the above program,

  • Statement stack<int> st1 creates an empty stack of integers. Elements are later added into st1.
  • Statement stack<int> st2 (s1) creates another stack st2 with the same elements as st1.

Basic Operations

Here are the basic operations that can be performed on a stack:

1. Inserting Elements

In stack, new elements can only be inserted at the top of the stack by using push() method. There is no way to inserting element at any other position of the stack.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     stack<int> st;          // Inserting element top of the stack     st.push(10);     st.push(20);     st.push(30);     st.push(40);          while(!st.empty()) {         cout << st.top() << " ";         st.pop();     }     return 0; } 

Output
40 30 20 10 
Push-Operation-in-Stack-(1)

2. Accessing Elements

Only the top element of the stack can be accessed using top() method. We can’t access any middle element of stack.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     stack<int> st;     st.push(10);     st.push(20);     st.push(30);     st.push(40);      // Accessing the top element     cout << st.top();     return 0; } 

Output
40
Top-or-Peek-Operation-in-Stack-(1)

3. Deleting Elements

In stack, only the top element of the stack can be deleted by using pop() method in one operation. To delete any other element, we have to first delete all the elements inserted after that element (i.e. elements on top of the that element).

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     stack<int> st;     st.push(10);     st.push(20);     st.push(30);     st.push(40);          // Deleting top element     st.pop();          while(!st.empty()) {         cout << st.top() << " ";         st.pop();     }     return 0; } 

Output
30 20 10 
Pop-Operation-in-Stack-(1)

4. Pseudo Traversal

As any element other than the top element cannot be accessed in the stack, it cannot be actually traversed. But we can create a copy of it, access the top element and delete the top. By doing this till the copy stack is empty, we can effectively traverse without modifying the original stack.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     stack<int> st;     st.push(10);     st.push(20);     st.push(30);     st.push(40);          // Create a copy     stack<int> temp(st);          while(!temp.empty()) {         cout << temp.top() << " ";         temp.pop();     }     return 0; } 

Output
40 30 20 10 

Explanation: In the above program, pseudo-traversal is done by creating a copy of the st to avoid modifying the original stack. The while loop prints and removes elements from temp using top() and pop() till the stack is not empty.

Time Complexity

The below table lists the time complexity of the above operations on stack:

OperationTime Complexity
Insert an element (push)O(1)
Delete an element (pop)O(1)
Access top element (peek)O(1)
Traverse the stackO(n)

Other Common Operations

The following are some more operations on stack that helps you become more familiarize with it:

  • Check if a stack is empty
  • Check the Size of the Stack
  • Reverse a stack
  • Clear a stack
  • Copy One Stack to Another
  • Swap Two Stacks

Internal Working

Stack container provides the built-in implementation of the stack data structure in C++. It is implemented as container adapter built over other containers such as vectors, lists, etc. It uses the LIFO (Last In, First Out) principle to push and pop elements. The top element is always the most recently added element, and operations are limited to this end of the stack.

Note: Though stacks can be possibly implemented using vectors, its middle elements cannot be accessed due to LIFO restrictions.

All Member Functions

Following is the list of all member functions of std::stack class in C++:

Functions

Description

push()

Add an element top of the stack.

push_range()

Add range of elements at top of the stack.

top()

Access the top element of the stack.

pop()

Remove the top element of the stack.

emplace()

Add the constructs element in top of the stack.

size()

Returns the number of elements in the stack.

empty()

Checks if the stack is empty.

swap()

Swap two stacks.


Next Article
stack empty() and stack size() in C++ STL
author
kartik
Improve
Article Tags :
  • C++
  • Stack
  • cpp-containers-library
  • cpp-stack
  • cpp-stack-functions
  • STL
Practice Tags :
  • CPP
  • Stack
  • STL

Similar Reads

  • Stack in C++ STL
    In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally
    5 min read
  • stack empty() and stack size() in C++ STL
    The std::stack::size() and std::stack::empty() in C++ are built-in functions that are used to provide information about the size of the stack. They are the member functions of the std::stack container defined inside <stack> header file. stack::empty()The stack::empty() method is used to check
    2 min read
  • stack::push() and stack::pop() in C++ STL
    The stack::push() and stack::pop() method in stack container is used to insert and delete the element from the top of stack. They are the member functions of std::stack container defined inside <stack> header file. In this article, we will learn how to use stack::push() and stack::pop() method
    2 min read
  • stack top() in C++ STL
    In C++, the std::stack::top() is used to find the top element of the std::stack container. It is a member function of std::stack class defined inside the <stack> header file. In this article, we will learn how to find the top element of stack using stack::top() in C++. Example: [GFGTABS] C++ #
    2 min read
  • stack emplace() in C++ STL
    Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. stack::emplace() This function is used to insert a new element into the stack container, the new element is added on top o
    3 min read
  • stack swap() in C++ STL
    Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only. stack::swap()This function is used to swap the contents of one stack with another stack of same type but the size may vary. S
    2 min read
  • List of Stacks in C++ STL
    Prerequisite: List, Stack Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Syntax: list <Type> name_of_list; Stack are a type of container adaptor wit
    3 min read
  • Implementing Stack Using Class Templates in C++
    The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or
    5 min read
  • How to implement a Stack using list in C++ STL
    In this article, we will discuss how to implement a Stack using list in C++ STL. Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:1. Push: Push an element into the stack.2. Pop: Removes the element by following
    3 min read
  • Queue using Stacks
    Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations. Table of Content By Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Makin
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences