Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear a stack in c++ efficiently?

Tags:

c++

I have a c++ stack named pages. As I have no clear() function to clear a stack, I wrote the following code:

stack<string> pages; //here is some operation //now clearing the stack while(!pages.empty())     pages.pop(); 

Now my question: is there a better efficient way to clear the stack?

like image 641
Misbah Ahmad Avatar asked Oct 23 '16 10:10

Misbah Ahmad


People also ask

How do you clear an entire stack?

clear() method is used to remove all the elements from a Stack. Using the clear() method only clears all the element from the Stack and does not delete the Stack. In other words, we can say that the clear() method is used to only empty an existing Stack.

Is there a clear function for stack in C++?

stack::empty() function is an inbuilt function in C++ STL, which is defined in <stack>header file. empty() is used to check whether the associated container is empty or not and return true or false accordingly. The function checks the container should be empty means the size of the container should be 0.

In which order we can remove the elements in stack?

The order in which elements come off a stack gives rise to its alternative name, LIFO (last in, first out). Additionally, a peek operation may give access to the top without modifying the stack.

When stack is empty its size can be?

isEmpty: Returns true if the stack is empty, i.e., its size is zero; otherwise, it returns false.


1 Answers

In general you can't clear copying containers in O(1) because you need to destroy the copies. It's conceivable that a templated copying container could have a partial specialization that cleared in O(1) time that was triggered by a trait indicating the type of contained objects had a trivial destructor.

If you want to avoid loop.

pages=stack<std::string>(); 

or

stack<std::string>().swap(pages); 
like image 181
v78 Avatar answered Sep 23 '22 07:09

v78