Is there any way in C++ to clear a queue or a stack efficiently without popping it O(n) times?

Quora Feeds

Active Member
Kelly Martin

In the current C++ standard library, both "stack" and "queue" are container adaptors, which means the stack adaptor goes on top of some other container class. Neither the stack nor the queue adaptor classes provide a method to empty their contents at one go, and neither provides a means to get at the underlying container object, so there is no way via either of these adaptor classes to empty the underlying container all at once.

If you want to be able to do this, you'll have to use one of the standard container classes (e.g. deque, vector, list) directly, or use a modified version of the adapter class that exposes the "clear" method from the underlying container or gives you direct access to the underlying container object. The latter approach violates encapsulation and may lead to unexpected results, especially if you mix using the adaptor methods with methods on the underlying container.

See Questions On Quora

Continue reading...
 
Top