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.