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

I don't think there is a more efficient way. A stack is a well defined data type, specifically designed to operate in a LIFO context, and not meant to be emptied at once. For this you could use vector or deque (or list), which are basically the underlying containers; a stack is in fact a container adaptor. Please see this C++ Reference for more information.

If you don't have a choice, and you have to use stack, then there is nothing wrong with the way you do it. Either way, the elements have to be destroyed if they were constructed, whether you assign a new empty stack or pop all elements out or whatever.

I suggest to use a vector instead; it has the operations you need indeed:

  • size (or resize)
  • empty
  • push_back
  • pop_back
  • back
  • clear

It is just more convenient, so you can use the clear method. Not sure if using vector is really more performant; the stack operations are basically the same.


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

Tags:

C++