stack empty() and stack size() in C++ STL
The std::stack::size() and std::stack::empty() in C++ are built-in functions that are used to provide information about the size of the stack. They are the member functions of the std::stack container defined inside <stack> header file.
stack::empty()
The stack::empty() method is used to check whether the stack is empty or not.
// C++ program to illustrate how to use
// stack::empty() function
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
// Checking if the stack st is empty
if (st.empty())
cout << "Stack is Empty" << endl;
else
cout << "Stack is NOT Empty" << endl;
// Inserting an element
st.push(11);
// Again checking if the stack st is empty
if (st.empty())
cout << "Stack is Empty" << endl;
else
cout << "Stack is NOT Empty" << endl;
return 0;
}
Output
Stack is Empty Stack is NOT Empty
Syntax
st.empty();
Parameters
- This function does not take any parameter.
Return Value
- Returns true if the stack is empty.
- Returns false if the stack is not empty.
stack::size()
The stack::size() method is used to find the number of elements in the stack container.
// C++ program to illustrate how to use stack::size()
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
st.push(11);
st.push(13);
st.push(9);
// Finding the size of the stack st
int n = st.size();
cout << "Size : " << n << endl;
return 0;
}
Output
Size : 3
Syntax
st.size();
Parameters
- This function does not take any parameters.
Return Value
- Returns the number of element present in the stack container.
- If there are no elements in the stack, returns 0.
Difference Between stack::size() and stack::empty()
Both the stack::size() and stack::empty() methods are give the information about the size of stack, but there are some differences between them which are listed below:
stack::empty() | stack::size() |
---|---|
It is used to return whether the stack is empty or not. | It is used to return the number of elements in the stack. |
Its syntax is:- | Its syntax is:- |
Its return type is of boolean. | Its return type is of integer. |