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

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

Leave a Comment