The empty function in C++ Stack is employed to determine if the container is devoid of any elements. Prior to retrieving elements from the stack, it is common practice for programmers to verify if the stack is empty. This approach offers benefits in terms of memory usage and efficiency.
Syntax
bool empty() const;
Parameters
There are no parameters present in this scenario. The function is specifically designed for testing purposes, therefore it is directly executed on the stack without any arguments being supplied.
Return value
If the specified container is devoid of content, the function will output 'true'; otherwise, it will output 'false'. This function serves the sole purpose of conducting tests and determines its return value based on the test outcomes.
Example 1
//The following code snippet is utilized to check if a 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 is: " << sum;
return 0;
}
return 0;
}
Output:
Result is: 55
Example 2
//The following code snippet is utilized to identify if a container is empty.
#include <iostream>
#include <stack>
using namespace std;
int main()
{
std::stack<int> newstack;
newstack.push(69);
//Checking whether the stack is empty
if(newstack.empty())
{
cout<<"The stack is empty, insert some elements to keep going";
}
else
{
cout<<"Elements are present in the stack";
}
return 0;
}
Output:
Elements are present in the stack
Complexity
The function serves the sole purpose of identifying if the container is empty, therefore it does not take any arguments and operates with constant complexity.
Data races
Only the storage unit is interacted with. The stack is accessed to verify the existence of items. This function doesn't interact with every single item, but rather quickly checks if the storage unit is completely empty or contains any elements.
Exception Safety
Assurance is given that the actions carried out on the container object below are equivalent.