Open In App

How to Clear a Stack in C++?

Last Updated : 15 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}

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:

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.

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;
}

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.

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;
}

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.


Next Article
Article Tags :
Practice Tags :

Similar Reads