Does anyone know why std::queue, std::stack, and std::priority_queue don't provide a clear()
member function? I have to fake one like this:
std::queue<int> q;
// time passes...
q = std::queue<int>(); // equivalent to clear()
IIRC, clear()
is provided by everything that could serve as the underlying container. Is there a good reason to not have the container adaptors provide it?
You CAN clear queues (and std::stack and priority_queue), as long as you inherit from it. The container is intentionally left protected to allow this.
I think it depends on the implementation - until recently Microsoft STL didn't have clear on several containers. (it does now, eg this quick google result)
However, clear() is often simply a call to erase(begin(), end()), so implement your own equivalent and use that instead.
I think the standard refers to clear as erasing over an iterator range, so the above is what most implementations will provide. (eg Dinkumware's)
Well, I think this is because
clear
was not considered a valid operation on a queue, a priority_queue or a stack (by the way, deque is not and adaptor but a container).So when using a queue, all you can do is push/pop elements; clearing the queue can be seen as a violation of the FIFO concept. Consequently, if you need to clear your queue, maybe it's not really a queue and you should better use a deque.
However, this conception of things is a little narrow-minded, and I think clearing the queue as you do is fair enough.
Deque has clear(). See, e.g., http://www.cplusplus.com/reference/stl/deque/clear.html.
However, queue does not. But why would you choose queue over deque, anyway?
(http://www.sgi.com/tech/stl/queue.html)
So I guess clear() is not a queue operation, then.
I'd say it's because container adaptors are not containers.
std::queue, std::deque, and std::priority_queue are container adaptors and only provide a small number of methods to access the underlying container.
You can clear the underlying container, so long as you can access it. To do this, create the underlying container to pass in to the apadptor constructor. For example:
Edit: additional info
I should also have warned you to tread carefully here as calling methods on the underlying container may break assumptions made by the adaptor. In that respect, the way you are currently clearng the queue seems preferable.