Why is there no clear() function for the inbuilt stack interface in C++?

Viewed 1121

I have to empty a stack before using it further more. I do understand that it can be done like:

while (!mystack.empty()) { mystack.pop(); }

Is there a specific reason for not having this function? or its just that the first time it was made, no one felt its requirement and has been just left out

Also, the stack interface in Java does have a clear() function.

3 Answers

While it would possibly be more readable to have an explicit .clear(), even without it you can empty a stack like this:

mystack = {};

As molbdnilo mentioned within the comments, you have to distinguish between standard containers and container adapters. std::stack is a container adapter, not a container. There are several reasons, why these adapters have to reduce their assumptions about characteristics of used inner container types as far as possible. A relevant one is time complexity (theoretical, accidental) for instance, that might differ a lot between possible underlying containers here. A further relevant aspect can be the requirement to be consistent to several access schemes within parallel working environments (parallel reads and writes), although that might not be relevant here specifically to the clear-functionality.

And in general, it follows a simple software design rule: Do not inflate top-level interfaces with too many assumptions about possible inner implementations and possible usage-scenarios that might occur for your data type but are not directly related to its core-characteristics. Directly clearing an 'abstract' stack can introduce a lot of confusion in doubt and error-prone misusage of objects of this type since a stack often represents more than just a simple partial ordering, it commonly represents a history. Semantically, a direct clear-operation can be seen as a design attack for several stack-related scenarios here: "Forget what I've done and thought so far with and about the stack, let's try something totally different..." Re-assigning is the superior approach therefore here in terms of proprtionality between the issues mentioned here since you explicitly introduce a totally new object (while the previous one might still live within a shared_ptr for instance somewhere else, unaffected by the clearing if required).

Run a while loop until the stack is empty to pop all the elements

while(!stack.empty()){
    stack.pop();
}
Related