The pop operation in a C++ Stack is employed to eliminate the element at the stack's top. It executes the removal task, adhering to the Last In First Out (LIFO) principle where the most recently added element is the first to be removed. Deletion within a stack always occurs from the top downwards to maintain the LIFO order.
Syntax
void pop()
Parameters
The function does not accept any parameters and is specifically designed for removing the top element. Due to the Last In, First Out (LIFO) principle of stacks, there is no need to explicitly mention which element to delete, as it is automatically assumed that the topmost element will be the one removed initially.
Return value
The function is specifically employed to eliminate elements from the stack and does not yield any output. Therefore, it can be concluded that the function's return type is void.
Example 1
//The code snippet showcases the implementation of the pop method in a stack data structure through the addition of basic integer elements.
#include <iostream>
#include <stack>
int main()
{
std::stack<int> newstack;
for(int j=0; j<5; j++)
newstack.push(j);
std::cout <<"Popping out elements?";
while (!newstack.empty () )
{
std::cout <<" " << newstack.top();
newstack.pop();
}
std::cout<<"\n";
return 0;
}
Output:
Popping out elements... 4 3 2 1 0
Example 2
The script showcases the functionality of the pop method in a stack through the addition of basic integer values.
#include <iostream>
#include <stack>
int main()
{
std::stack<int> newstack;
newstack.push(11);
newstack.push(22);
newstack.push(33);
newstack.push(44);
std::cout << "Popping out elements?";
newstack.pop();
newstack.pop();
while (!newstack.empty () )
{
std::cout << " "<< newstack.top();
newstack.pop();
}
std::cout<<"\n";
return 0;
}
Output:
Popping out elements... 22 11
Example 3
//This code snippet showcases the implementation of the pop method in a stack data structure through the addition of basic integer values.
#include <iostream>
#include <stack>
int main()
{
std::stack<int> newstack;
newstack.push(69);
newstack.push(79);
newstack.push(80);
newstack.push(85);
newstack.push(90);
while (!newstack.empty () )
{
std::cout<< " " << newstack.top ();
newstack.pop();
}
return 0;
}
Output:
90 85 80 79 69
Complexity
The function's complexity remains constant since it solely executes either a pop or delete operation on the stack's top without adding to the complexity.
Data races
The adjustment impacts both the container and its contents. When a deletion operation is performed, the change is seen in the element at the topmost position, causing the top position to shift down by one unit. This can be illustrated as top=top--.
Exception Safety
A guarantee is given that matches the operations carried out on the container object.