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.
Elyasin
source share