The Wayback Machine - https://web.archive.org/web/20241117072914/https://www.geeksforgeeks.org/stack-in-cpp-stl/
Open In App

Stack in C++ STL

Last Updated : 14 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Topics:
Solve Problem
Basic
65.59%
5.8K

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 uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements. 

If there is confusion in remembering the basic difference between stack and queue, then just have a real life example for this differentiation, for stack, stacking of books we can take the top book easily and for queue remember when you have to stand in queue front of ATM for taking out the cash, then first person near to ATM has the first chance to take out the money from ATM. So, queue is the FIFO (First In First Out) type working.

Stack Syntax:-

For creating  a stack, we must include the <stack> header file in our code. We then use this syntax to define the std::stack:

template <class Type, class Container = deque<Type> > class stack;

Type – is the Type of element contained in the std::stack. It can be any valid C++ type or even a user-defined type.

Container – is the Type of underlying container object.

Member Types:-

value_type- The first template parameter, T. It denotes the element types.

container_type- The second template parameter, Container. It denotes the underlying container type.

size_type- Unsigned integral type.
  
The functions associated with stack are: 
empty() – Returns whether the stack is empty – Time Complexity : O(1) 
size() – Returns the size of the stack – Time Complexity : O(1) 
top() – Returns a reference to the top most element of the stack – Time Complexity : O(1) 
push(g) – Adds the element ‘g’ at the top of the stack – Time Complexity : O(1) 
pop() – Deletes the most recent entered element of the stack – Time Complexity : O(1) 

 
C++
#include <iostream> 
#include <stack>
using namespace std;
int main() {
    stack<int> stack;
    stack.push(21);// The values pushed in the stack should be of the same data which is written during declaration of stack
    stack.push(22);
    stack.push(24);
    stack.push(25);
    int num=0;
      stack.push(num);
    stack.pop();
    stack.pop();
      stack.pop();
  
    while (!stack.empty()) {
        cout << stack.top() <<" ";
        stack.pop();
    }
}

Output
22 21 

 Time complexity: The time complexity of this program is O(N), where N is the total number of elements in the stack. The while loop iterates N times, popping elements from the stack and printing them.

 Space complexity:The space complexity of this program is O(N), where N is the total number of elements in the stack. The stack data structure uses space proportional to the number of elements stored in it. In this case, the maximum size of the stack is 5, so the space complexity is constant and can be considered as O(1) as well.

For a complete understanding of stacks and other STL containers, explore our Complete C++ Course, which provides hands-on practice with data structures.

 

Code Explanation:

  1. Include the iostream header file or <iostream> in our code to use its functions.
  2. Include the stack header file in our code to use its functions if already included <iostream> then no need of stack header file because it has already inbuilt function in it.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should be added within this function.
  5. Create a stack to store integer values.
  6. Use the push() function to insert the value 21 into the stack.
  7. Use the push() function to insert the value 22 into the stack.
  8. Use the push() function to insert the value 24 into the stack.
  9. Use the push() function to insert the value 25 into the stack.
  10. Use a integer variable “num” to enter a variable value. Here its value is 0, but we can assign any integer value using cin >> num.
  11. Use the push() function to insert the value of “num” variable.
  12. Use the pop() function to remove the top element from the stack, that is, 25. The top element now becomes 24.
  13. Use the pop() function to remove the top element from the stack, that is, 24. The top element now becomes 22.
  14. Use a while loop and empty() function to check whether the stack is NOT empty. The ! is the NOT operator. So, when stack is not empty then empty() function will return false and NOT operator convert it in true and the while loop keep running. But, when the stack become empty then empty() function will return true and NOT operator will make it false and the loop come to an end.
  15. Printing the current contents of the stack on the console.
  16. Call the pop() function on the stack.
  17. End of the body of the while loop.
  18. End of the main() function body.

List of functions of Stack: 




Similar Reads

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. In this article, we will learn how to use stack::size() and stack::empty() in C++. Table of Content std::st
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() methods in C++. stack::push()The stack::push() function
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 of the stack. Syntax : stackname.emplace(value) Par
3 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 the LIFO order.3. Top: Returns the element present
3 min read
Stack-buffer based STL allocator
It is absolutely possible to develop a stack allocator that completely complies with C++11 and C++14. However, you must take into account some of the implications of stack allocation's implementation, semantics, and interactions with common containers. Here is a fully compliant stack allocator for C++11 and C++14:- Stack buffer: When information wr
4 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. Syntax : stackname1.swap(stackname2)Parameters: The
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++ #include <bits/stdc++.h> using namespace std;
2 min read
Stack Permutations (Check if an array is stack permutation of other)
A stack permutation is a permutation of objects in the given input queue which is done by transferring elements from the input queue to the output queue with the help of a stack and the built-in push and pop functions. The rules are: Only dequeue from the input queue.Use inbuilt push, and pop functions in the single stack.Stack and input queue must
15+ min read
Reversing a Stack with the help of another empty Stack
Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach 1: Follow the steps below to solve the problem: Initialize an empty stack.Po
8 min read
Sort a stack using a temporary stack
Given a stack of integers, sort it in ascending order using another temporary stack. Examples: Input : [34, 3, 31, 98, 92, 23] Output : [3, 23, 31, 34, 92, 98] Input : [3, 5, 1, 4, 2, 8] Output : [1, 2, 3, 4, 5, 8] Recommended PracticeSort a stackTry It! Algorithm: Create a temporary stack say tmpStack.While input stack is NOT empty do this: Pop an
6 min read
Find maximum in stack in O(1) without using additional stack in Python
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack in Python. Examples: Input: Consider the following SpecialStack 16 –> TOP29151918When getMax() is called it should return 29, which is the maximum element in the current stack. If we do pop two times on stack, the stack becom
3 min read
Rotate in C++ STL
The function is defined in header <algorithm>. It rotates the order of the elements in the range [first, last], in such a way that the element pointed by the middle becomes the new first element. Function Template : void rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last) first, last : Forward Iterators to the initial
3 min read
deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
list::push_front() and list::push_back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::push_front() push_front() function is used to push elements into a list from the front. The n
4 min read
list::pop_front() and list::pop_back() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::pop_front() pop_front() function is used to pop or remove elements from a list from the front
4 min read
list::front() and list::back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::front() This function is used to reference the first element of the list container. This func
3 min read
list::empty() and list::size() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::empty()empty() function is used to check if the list container is empty or not. Syntax : list
3 min read
list::remove() and list::remove_if() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::remove() remove() function is used to remove all the values from the list that correspond to
3 min read
queue::empty() and queue::size() in C++ STL
Queue is a type of container adaptor that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::empty() empty() function is used to check if the queue container is empty or not. SyntaxqueueName.empty()ParametersThis function does not accept any parameter.Return Val
4 min read
deque::pop_front() and deque::pop_back() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::pop_front() pop_front()
4 min read
queue::front() and queue::back() in C++ STL
Queue are a type of container adaptors which operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::front() This function is used to reference the first or the oldest element of the queue container. This function can be used to fetch the first element of a queue.Syn
3 min read
forward_list::push_front() and forward_list::pop_front() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps tr
4 min read
map::clear() in C++ STL
Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key. map::clear() clear() function is used to remove all the elements from the map container and thus leaving it's size 0. Syntax: map1.clear() where map1 is the name of the map. Parameters: No parameters ar
2 min read
priority_queue::empty() and priority_queue::size() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extr
4 min read
priority_queue::top() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest element by default. We can also make a priority queue
3 min read
array::front() and array::back() in C++ STL
Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::front() This function is used to reference the first element of the array container. This function can be used to fetch the first element of an array. Synt
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
deque::clear() and deque::erase() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::clear() The clear()
5 min read
list::clear() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::clear()clear() function is used to remove all the elements of the list container, thus making
1 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
three90RightbarBannerImg