In C++, clearing a stack means removing all element from the stack container leaving it empty. In this article, we will learn how to clear a stack in C++.
The most efficient method to clear a stack is by assigning the new empty stack to our original stack container. Let's take a look at the code example:
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> s;
s.push(1);
s.push(5);
s.push(4);
// Initial size of the stack
cout << s.size() << endl;
// Assigning the new empty stack
s = stack<int>();
// Final size of the stack
cout << s.size() << endl;
return 0;
}
Output
3 0
This method destroys the previously stored elements.
There are also a few other methods to clear a stack in C++. They are given below:
Table of Content
Using Stack swap() Method
A new empty stack container is swapped with original std::stack container by using stack swap() function. This method is similar to the previous method but allows us to save the stack elements before clearing it.
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> s;
s.push(1);
s.push(5);
s.push(4);
// Initial size of the stack
cout << s.size() << endl;
// Swap the stack with new empty stack
stack<int> s1;
s.swap(s1);
// Final size of the stack
cout << s.size() << endl;
return 0;
}
Output
3 0
Using Stack pop() Method
The stack pop() method removes the top element of the stack. It can be used to clear the stack by popping all the elements one by one in a loop until the stack is empty.
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> s;
s.push(1);
s.push(5);
s.push(4);
// Initial size of the stack
cout << s.size() << endl;
// Removing all elements from stack one by one
while (!s.empty())
s.pop();
// Final size of the stack
cout << s.size() << endl;
return 0;
}
Output
Stack is Empty
Explanation: In the above code, we remove all elements from stack container one by one till stack empty() does not returns true.