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?
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.
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.
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.
isEmpty: Returns true if the stack is empty, i.e., its size is zero; otherwise, it returns false.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With