C++ Standard Library C++ STL Library

C++ <stack> - push() Function



The C++ stack::push function is used to add a new element at the top of the stack. In a stack, addition and deletion of a element occurs from the top of the stack. Hence, The most recently added element will be the top element of the stack. Addition of new element always occurs after its most recently added element and every addition results into increasing the container size by one.

Syntax

void push (const value_type& val);
void push (const value_type& val);
void push (value_type&& val);

Parameters

val Specify the value which need to be added in the stack.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the stack::push function is used to add new elements at the top of the stack called MyStack.

#include <iostream>
#include <stack>
using namespace std;
 
int main (){
  stack<int> MyStack;

  //add new elements in the stack
  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);
  MyStack.push(40);
  MyStack.push(50);

  cout<<"MyStack contains:";
  while (!MyStack.empty()) {
    cout<<" "<<MyStack.top();
    MyStack.pop();
  }
  return 0;
}

The output of the above code will be:

MyStack contains: 50 40 30 20 10

❮ C++ <stack> Library