How can I clear the stack in C ++ efficiently?

I have a C ++ stack with page names. Since I don't have a clear () function to clear the 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: is there a more efficient way to clear the stack? Thanks in advance.

+7
c ++
source share
2 answers

Generally, you cannot clear copies of containers in O (1) because you need to destroy copies. It can be assumed that the template copying container may have a partial specialization cleared O (1) times, which was caused by a sign indicating that the type of contained objects has a trivial destructor.

If you want to avoid a loop.

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

or

 stack<std::string>().swap(pages); 
+12
source share

I do not think there is a more efficient way. A stack is a well-defined data type that is specifically designed to work in the LIFO context and is not intended to be emptied immediately. For this, you can use vector or deque (or list ), which are basically basic containers; a stack is actually a container adapter. For more information, see This C ++ Reference .

If you have no choice and you must use the stack, then there is nothing wrong with how you do it. In any case, the elements must be destroyed if they were built, regardless of whether you assign a new empty stack or drop out all the elements or something else.

I suggest using vector instead; it really has the necessary operations:

  • size (or resizing)
  • empty
  • push_back
  • pop_back
  • back
  • clear,

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

+8
source share

All Articles