English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of Stack pop() function

C++ STL Stack (Stack)

C ++The stack pop() function is used to delete the top element of the stack. This function performs the deletion operation. The deletion from the stack starts from the top. The most recently inserted element is deleted first. The stack follows the LIFO principle, that is, last in, first out, so the pop operation follows the above order.

Syntax

void pop()

Parameters

This function does not take any parameters and is used only to delete the top element. Similarly, since the stack follows the LIFO principle, we do not need to specify the element to be deleted, as the top element will be deleted first by default.

Return value

This function is used only to delete elements from the stack and does not return any value. Therefore, we can say that the return type of this function is void.

Instance1

//This program is used to demonstrate the usage of the pop() function of the stack by inserting simple integer values.

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> newstack; 
	for (int j = 0; j <5; j++)
	newstack.push(j);
	cout << "Pop element?";
	while (!newstack.empty())
	{
		cout << "\t" << newstack.top();
		newstack.pop();
	}
	cout << "\n";
	return 0;
}

Output:

Pop elements... 4 3 2 1 0

Instance2

//This program is used to demonstrate the usage of the pop() function of the stack by inserting simple integer values.

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> newstack; 
	newstack.push(11);
	newstack.push(22);
	newstack.push(33);
	newstack.push(44);
	cout << "Pop element?";
	newstack.pop();
	newstack.pop();
	while (!newstack.empty())
	{
		cout << "\t" << newstack.top();
		newstack.pop();
	}
	cout << "\n";
	return 0;
}

Output:

Pop elements... 22 11

Instance3

//This program is used to demonstrate the usage of the pop() function of the stack by inserting simple integer values.

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> newstack;
	newstack.push(69);
	newstack.push(79);
	newstack.push(80);
	newstack.push(85);
	newstack.push(90);
	while (!newstack.empty())
	{
		cout << " " << newstack.top();
		newstack.pop();
	}
	return 0;
}

Output:

90 85 80 79 69

Complex

The complexity of this function is constant, as this function only performs pop or delete operations at the top of the stack without adding any complexity.

Data Races

The container and the elements it contains have been modified. By the deletion operation, the changes are reflected on the element at the top position, and the top position moves down by one unit. It can be proven that top = top--.

Exception Safety

Provides guarantees equivalent to operations performed on underlying container objects.

C++ STL Stack (Stack)