stack::push() and stack::pop() in C++ STL (original) (raw)

Last Updated : 11 Jan, 2025

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 <s****tack**> 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 is used to insert or 'push' an element at the top of stack container. This increases the size of stack container by 1.

**Syntax

st.**push(_val);

where, **st is the name of the stack

**Parameters

**Return Value

Managing data with stacks is essential for various applications.

Example of stack::push()

C++ `

// C++ program to show how to use the stack::push() // method to insert elements in a stack #include <bits/stdc++.h> using namespace std;

int main() { stack st;

// Inserting an element in stack
// with push() method
st.push(0);

  // Inserting more elements in the stack
st.push(1);
st.push(2);

  // Printing stack
while (!st.empty()) {
    cout << ' ' << st.top();
    st.pop();
}
  return 0;

}

`

**Time Complexity: O(1)
**Auxiliary Space: O(1)

stack::pop()

The **stack::pop() function to remove or 'pop' the element from the top of stack. As we are only inserting and removing from the top, the most recently inserted element will be removed first. This decreases the size of stack container by 1.

**Syntax

st.**pop()

**Parameters

**Return value

Example of stack::pop()

C++ `

// C++ program to show how to use the stack::pop() // method #include <bits/stdc++.h> using namespace std;

int main() { stack st; st.push(1); st.push(2); st.push(3); st.push(4);

// Deleting 2 element from the top
st.pop();
st.pop();

while (!st.empty()) {
    cout << ' ' << st.top();
    st.pop();
}

  return 0;

}

`

**Time Complexity: O(1)
**Auxiliary Space: O(1)