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 push() and pop() in C++ STL

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.

Similar Reads

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 header file. The element is added to the stack container and the size of the stack is increased by 1.Syntax:...

stack::pop()

...