The Wayback Machine - https://web.archive.org/web/20240916025114/https://www.geeksforgeeks.org/stack-empty-and-stack-size-in-c-stl/
Open In App

stack empty() and stack size() in C++ STL

Last Updated : 30 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.

stack::empty()

empty() function is used to check if the stack container is empty or not.

Syntax :

stackname.empty()
Parameters :
No parameters are passed.
Returns :
True, if stack is empty
False, Otherwise

Examples:

Input :   mystack
mystack.empty();
Output : True

Input : mystack = 1, 2, 3
Output : False

Errors and Exceptions

1. Shows error if parameter is passed

2. Shows no exception throw guarantee. 

CPP




// CPP program to illustrate
// Implementation of empty() function
#include <iostream>
#include <stack>
using namespace std;
 
int main()
{
    stack<int> mystack;
    mystack.push(1);
 
    // Stack becomes 1
 
    if (mystack.empty()) {
        cout << "True";
    }
    else {
        cout << "False";
    }
    return 0;
}


Output:

False

Application : Given a stack of integers, find the sum of the all the integers.

Input : 1, 8, 3, 6, 2
Output: 20

Algorithm

1. Check if the stack is empty, if not add the top element to a variable initialised as 0, and pop the top element.

2. Repeat this step until the stack is empty.

3. Print the final value of the variable. 

CPP




// CPP program to illustrate
// Application of empty() function
#include <iostream>
#include <stack>
using namespace std;
 
int main()
{
    int sum = 0;
    stack<int> mystack;
    mystack.push(1);
    mystack.push(8);
    mystack.push(3);
    mystack.push(6);
    mystack.push(2);
 
    // Stack becomes 1, 8, 3, 6, 2
 
    while (!mystack.empty()) {
        sum = sum + mystack.top();
        mystack.pop();
    }
    cout << sum;
    return 0;
}


Output:

20
stack::size()

size() function is used to return the size of the stack container or the number of elements in the stack container. Syntax :

stackname.size()
Parameters :
No parameters are passed.
Returns :
Number of elements in the container.

Examples:

Input :   mystack = 0, 1, 2
mystack.size();
Output : 3

Input : mystack = 0, 1, 2, 3, 4, 5
mystack.size();
Output : 6

Errors and Exceptions

1. Shows error if a parameter is passed.

2. Shows no exception throw guarantee. 

CPP




// CPP program to illustrate
// Implementation of size() function
#include <iostream>
#include <stack>
using namespace std;
 
int main()
{
    int sum = 0;
    stack<int> mystack;
    mystack.push(1);
    mystack.push(8);
    mystack.push(3);
    mystack.push(6);
    mystack.push(2);
 
    // Stack becomes 1, 8, 3, 6, 2
 
    cout << mystack.size();
 
    return 0;
}


Output:

5

Application : Given a stack of integers, find the sum of the all the integers.

Input : 1, 8, 3, 6, 2
Output: 20

Algorithm

1. Check if the size of the stack is zero, if not add the top element to a variable initialised as 0, and pop the top element.

2. Repeat this step until the stack size becomes 0.

3. Print the final value of the variable. 

CPP




// CPP program to illustrate
// Application of size() function
#include <iostream>
#include <stack>
using namespace std;
 
int main()
{
    int sum = 0;
    stack<int> mystack;
    mystack.push(1);
    mystack.push(8);
    mystack.push(3);
    mystack.push(6);
    mystack.push(2);
 
    // Stack becomes 1, 8, 3, 6, 2
 
    while (mystack.size() > 0) {
        sum = sum + mystack.top();
        mystack.pop();
    }
    cout << sum;
    return 0;
}


Output:

20

Let us see the differences in a tabular form -:

 

stack empty() stack size()
1.

It is  used to return whether the stack is empty

It is used to return the number of elements in the stack.

2.

Its syntax is -:

empty();

Its syntax is -:

size();

3.

Its return type is of boolean.

Its return type is of integer.

4.

It does not take any parameters.

It does not take any parameters.

5.

Its complexity is constant.

Its complexity is constant.



Previous Article
Next Article

Similar Reads

list::empty() and list::size() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::empty()empty() function is used to check if the list container is empty or not. Syntax : list
3 min read
queue::empty() and queue::size() in C++ STL
Queue is a type of container adaptor that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. queue::empty() empty() function is used to check if the queue container is empty or not. SyntaxqueueName.empty()ParametersThis function does not accept any parameter.Return Val
4 min read
priority_queue::empty() and priority_queue::size() in C++ STL
Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extr
4 min read
vector::empty() and vector::size() in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::empty() The empty() function is used to check if the vector container is empty or not.Syntax : vectorname.empty() Parameters : No parameters are p
5 min read
Deque::empty() and deque::size() in C++ STL
Deque or Double Ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed in the deque. deque::empty() emp
4 min read
Reversing a Stack with the help of another empty Stack
Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack. Examples: Input: stack = {1, 2, 3, 4, 5} Output: 1 2 3 4 5 Explanation: Input Stack: 5 4 3 2 1 Reversed Stack: 1 2 3 4 5 Input: stack = {1, 3, 5, 4, 2} Output: 1 3 5 4 2 Approach 1: Follow the steps below to solve the problem: Initialize an empty stack.Po
8 min read
forward_list::front() and forward_list::empty() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps tr
3 min read
array::empty() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::empty() empty() function is used to check if the array container is empty or not. Syntax : arrayname.empty() Parameters : No parameters are passed. Returns
1 min read
map::empty() in C++ STL
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. map::empty() empty() function is used to check if the map container is empty or not. Syntax : mapname.empty() Parameters : No parameters are passed. Returns : True, if map is empty
1 min read
set::empty() in C++ STL
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. set::empty() empty() function is used to check if the set container is
2 min read
list empty() function in C++ STL
The list::empty() is a built-in function in C++ STL that is used to check whether a particular list container is empty or not. This function does not modify the list, it simply checks whether a list is empty or not, i.e. the size of the list is zero or not. Syntaxlist_name.empty() Parameters This function does not accept any parameter, it simply ch
1 min read
multiset empty() function in C++ STL
The multiset::empty() function is a built-in function in C++ STL which checks if the multiset is empty or not. It returns true if the multiset is empty, else it returns false. Syntax: multiset_name.empty() Parameters: The function does not accept any parameter. Return Value: The function returns true if the multiset is empty, else it returns false.
1 min read
unordered_multiset empty() function in C++STL
The unordered_multiset::empty() is a built-in function in C++ STL which returns a boolean value. It returns true if the unordered_multiset container is empty. Otherwise, it returns false. Syntax: unordered_multiset_name.empty() Parameters: The function does not accepts any parameter. Return Value: It returns a boolean value which denotes whether a
2 min read
unordered_multimap empty() function in C++ STL
The unordered_multimap::empty() is a built-in function in C++ STL which returns a boolean value. It returns true if the unordered_multimap container is empty. Otherwise, it returns false. Syntax: unordered_multimap_name.empty() Parameters: The function does not accept any parameter. Return Value: It returns a boolean value which denotes whether a u
2 min read
match_results empty() in C++ STL
The match_results::empty() is a inbuilt function in C++ which returns True if the smatch object contains no matches.Syntax: smatch_name.empty() Note: smatch_name is an object of match_results class. Parameters:This function accept no parameters.Return value: This function returns true when the object is default-constructed or else return false if a
2 min read
multimap empty() function in C++ STL
The multimap::empty() is a boolean type observer function in C++ STL which tells whether the container is empty or not. This function returns true when the multimap container is empty (i.e. the size of the container is 0). Being an observer function it does not modify the multimap in any way. Syntax: multimap1.empty() Return Value: This method retu
1 min read
unordered_map empty in C++ STL
unordered_map::empty() function is used to check whether container size is zero or not. If container size is zero then it return TRUE otherwise it return FALSE. Syntax: unordered_map_name.empty() Parameters: This function does not accept any parameter Return type: This function returns boolean value TRUE or FALSE. Examples: Input: ump = { {1, 2}, {
2 min read
unordered_set empty() function in C++ STL
The unordered_set::empty is a built-in function in C++ STL which is used to check if an unordered_set container is empty or not. It returns True if the unordered_set container is empty, otherwise it returns False. Syntax: set_name.empty()Parameters: This function does not accepts any parameter. Return Value: It returns a boolean value True if the u
2 min read
Why does empty Structure has size 1 byte in C++ but 0 byte in C
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax for creating a structure is as shown below: Syntax- struct structureName{ member1; member2; member3; . . . memberN; }
3 min read
Why is the Size of an Empty Class Not Zero in C++?
When the structure was introduced in C, there was no concept of Objects at that time. So, according to the C standard, it was decided to keep the size of the empty structure to zero. In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e.
4 min read
Reversing a Stack using two empty Stacks
Given a stack S, the task is to reverse the stack S using two additional stacks. Example: Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1→top2345After reversing it, use two additional stacks:5→top4321 Input: S={1, 25, 17}Output: 17 25 1 Approach: Follow the steps below to solve the problem: Create two additional empty sta
6 min read
Difference Between Size and Capacity of a Vector in C++ STL
In this article, we are going to study the difference between the size and capacity of a vector in C++ STL. The size of the vector is defined as the total number of elements present in the vector. Vector is a dynamic array so it changes with the user input, unlike the static arrays which we define with the subscript operators "[]" which remain cons
3 min read
Stack push() and pop() in C++ STL
Stacks are a type of container adaptors that follow LIFO(Last In First Out) property, where a new element is added at one end and an element(at the top) is removed from that end only. Basically, the insertion and deletion happen on the top of the stack itself. stack::push() push() function is used to insert or 'push' an element at the top of the st
4 min read
array::size() in C++ STL
Array classes are generally more efficient, light-weight and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::size() size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname.size() Parameter
1 min read
map::size() in C++ STL
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values. map::size() In C++, size() function is used to return the total number of elements present in the map. Syntax: map_name.size() Return Value: It returns the number of elements presen
1 min read
set::size() in C++ STL
Sets are containers that store unique elements following a specific order. Internally, the elements in a set are always sorted. Sets are typically implemented as binary search trees. The set class provides a member function, set::size() function is used to return the size of the set container or the number of elements in the set container. Syntaxse
1 min read
bitset size() in C++ STL
bitset::size() is a built-in STL in C++ which returns the total number of bits. Syntax: bitset_name.size() Parameter: The function accepts no parameter. Return Value: The function returns an integral value which signifies the number of bits. It eventually returns the size that has been given while initializing the bitset. Below programs illustrate
2 min read
list size() function in C++ STL
The list::size() is a built-in function in C++ STL that is used to find the number of elements present in a list container. That is, it is used to find the size of the list container.Syntax: list_name.size(); Time Complexity - Linear O(1) as per c++11 standard. Possible because the implementation maintains the size field. Parameters: This function
1 min read
multimap size() function in C++ STL
The multimap::size() is a built-in function in C++ STL which returns the number of elements in the multimap container. Syntax: multimap_name.size() Parameters: The function does not accept any parameter. Return Value: This function returns the number of elements a multimap container has. C/C++ Code // C++ function for illustration // multimap::size
1 min read
multiset size() in C++ STL with Examples
The multiset::size() is a built-in function in C++ STL which returns the number of elements in the multiset container. Syntax: multiset_name.size() Parameters: The function does not accept any parameters. Return Value: The function returns the number of elements in the multiset container. Below programs illustrate the above function: Program 1: //
2 min read