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

C++ Usage and Example of Stack empty() Function

C++ STL Stack (Stack)

C ++ The Stack empty() function is used to test if the container is empty. In many cases, before extracting the actual elements from the stack, programmers prefer to check if the stack indeed contains some elements. This is beneficial in terms of storage and cost.

Syntax

bool empty() const;

Parameters

No parameters. Since this function is only used for testing purposes, it is directly applied to the stack. Therefore, no parameters are passed.

Return value

If the referenced container is empty, this method returns "true", otherwise it returns "false". This method is only used for testing purposes, so the returned value is based on the test result.

Instance1

//The following program is used to check if the container is empty.

#include <iostream>
#include <stack>
int main()
{
	std::stack<int> newstack;
	int sum=0;
	for (int j=1; j<=10; j++)
	newstack.push(j);
	while (!newstack.empty())
	{
		sum += newstack.top();
		newstack.pop();
	}
	std::cout << "Result: " << sum;
	return 0;
}
return 0;
}

Output:

Result: 55

Instance2

//The following program is used to check if the container is empty.

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	std::stack<int> newstack;
	newstack.push(69);
	//Check if the stack is empty
	if(newstack.empty())
	{
		cout << "Stack is empty, insert some elements to continue";
	}
	else
	{
		cout << "Element appears in the stack";
	}
	return 0;
}

Output:

Elements appear in the stack

Complex

This function is used only to detect whether the container is empty and therefore does not accept any parameters and has constant complexity.

Data Races

Only access the container. Access the stack to check for the existence of elements. Not all elements can be accessed through this function, but you can check at a glance whether the container is empty or not.

Exception Safety

It provides the same guarantees as operations performed on the underlying container objects.

C++ STL Stack (Stack)