The Wayback Machine - https://web.archive.org/web/20240914094052/https://www.geeksforgeeks.org/stack-push-and-pop-in-c-stl/
Open In App

Stack push() and pop() in C++ STL

Last Updated : 22 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Stacks are a type of container adaptors that follow LIFO(Last In First Out) property, where a new element is added at one end and an element(at the top) is removed from that end only. Basically, the insertion and deletion happen on the top of the stack itself.

stack::push()

push() function is used to insert or ‘push’ an element at the top of the stack. This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is added to the stack container and the size of the stack is increased by 1.
Syntax:

stackname.push(value)

Parameters: The value of the element to be inserted is passed as the parameter.
Result: Adds an element of value the same as that of the parameter passed at the top of the stack.

Examples: 

Input :   mystack
          mystack.push(6);
Output :  6
 
Input :   mystack
          mystack.push(0);
          mystack.push(1);
Output :  0, 1

Errors and Exceptions:

  • Shows an error if the value passed doesn’t match the stack type. 
  • Shows no exception throw guarantee if the parameter doesn’t throw any exception.

CPP




// CPP program to illustrate
// Implementation of push() function
  
#include <iostream>
#include <stack>
using namespace std;
  
int main()
{
    // Empty stack
    stack<int> mystack;
    mystack.push(0);
    mystack.push(1);
    mystack.push(2);
  
    // Printing content of stack
    while (!mystack.empty()) {
        cout << ' ' << mystack.top();
        mystack.pop();
    }
}


Output

 2 1 0

NOTE: Here, output is printed on the basis of LIFO property.

stack::pop()

The pop() function is used to remove or ‘pop’ an element from the top of the stack(newest or the topmost element in the stack). This is an inbuilt function from C++ Standard Template Library(STL). This function belongs to the <stack> header file. The element is removed from the stack container and the size of the stack is decreased by 1.
Syntax:

stackname.pop()

Parameters: No parameters are passed.

Result: Removes the newest element in the stack or basically the top element.

Examples: 

Input :   mystack = 0, 1, 2
          mystack.pop();
Output :  0, 1
 
Input :   mystack = 0, 1, 2, 3, 4, 5
          mystack.pop();
Output :  0, 1, 2, 3, 4

Errors and Exceptions:

  • Shows error if a parameter is passed. 
  • Shows no exception throw guarantee.

CPP




// CPP program to illustrate
// Implementation of pop() function
  
#include <iostream>
#include <stack>
using namespace std;
  
int main()
{
    stack<int> mystack;
    mystack.push(1);
    mystack.push(2);
    mystack.push(3);
    mystack.push(4);
     
   // Stack becomes 1, 2, 3, 4
  
    mystack.pop();
    mystack.pop();
   
   // Stack becomes 1, 2
  
    while (!mystack.empty()) {
        cout << ' ' << mystack.top();
        mystack.pop();
    }
}


Output

 2 1

Note: Here, output is printed on the basis of LIFO property.

Application: Given a number of integers, add them to the stack and find the size of the stack without using the size function. 

Input : 5, 13, 0, 9, 4
Output: 5

Approach: We can keep a counter variable that will keep track of the size of the stack. Whenever we push (add) elements into the stack then increment the counter that indicates the size of the stack has increased now and whenever we pop (remove) elements from the stack then decrement the counter that indicates decrement in size of the stack.

Algorithm: 

  • Push the given elements to the stack container one by one. 
  • Keep popping the elements of the stack until it becomes empty, and increment the counter variable. 
  • Print the counter variable.

CPP




// CPP program to illustrate
// Application of push()
// and pop() function
#include <iostream>
#include <stack>
using namespace std;
  
int main()
{
    int c = 0;
  
    // Empty stack
    stack<int> mystack;
    mystack.push(5);
    mystack.push(13);
    mystack.push(0);
    mystack.push(9);
    mystack.push(4);
    // stack becomes 5, 13, 0, 9, 4
  
    // Counting number of elements in queue
    while (!mystack.empty()) {
        mystack.pop();
        c++;
    }
    cout << c;
}


Output

5

 



Previous Article
Next Article

Similar Reads

priority_queue::push() and priority_queue::pop() 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
3 min read
queue push() and pop() in C++ STL
The queue is a type of container that operates in a First In First Out (FIFO) type of arrangement. Elements are inserted at the back(end) and are deleted from the front of the queue. For this purpose, the member functions queue::push() and queue::pop() are used respectively. In this article, we will discuss these queue::pop() and queue()::push() fu
4 min read
stack empty() and stack size() 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 and (top) an element is removed from that end only. stack::empty()empty() function is used to check if the stack container is empty or not. Syntax : stackname.empty()Parameters :No parameters are passed.Returns :True, if sta
3 min read
Why Doesn't std::queue::pop Return Value?
In C++, we use std::queue which is a container adapter in the standard template library (STL) and is used for managing a collection of elements in a FIFO (first-in, first-out) order. One common question that arises in our mind is why the pop function in std::queue does not return the value it removes from the queue. In this article, we will learn t
3 min read
stack top() 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 called the top of the stack, and an element is removed from the same end only. stack::top() top() function is used to reference the top(or the newest) element of the stack. Syntax : stackname.top() Parameters: No value is neede
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 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 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 membe
5 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
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
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
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
vector::front() and vector::back() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::front() This function can be used to fetch the first element of a vector container.Syntax : vectorname.front() Parameters : No value is needed to pass as
3 min read
vector::empty() and vector::size() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 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
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
forward_list::clear() and forward_list::erase_after() 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
vector::at() and vector::swap() in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::at() at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameter
4 min read