Last Updated : 23 Jul, 2025
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:
C++
#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;
}
This method destroys the previously stored elements.
There are also a few other methods to clear a stack in C++. They are given below:
Using Stack swap() MethodA 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.
C++
#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;
}
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.
C++
#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;
}
Explanation: In the above code, we remove all elements from stack container one by one till stack empty() does not returns true.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4