views:

130

answers:

3

Hi, I have requirement like this. For a function, i get input as a stream of numbers. I mean, function keeps on getting called with single number in each call. I am using queue for storing stream of numbers. I need to process a collected set of numbers only when some condition is satisfied. If condition is not satisfied i need to throw all the elements in the queue and then start storing new numbers in that. For emptying the queue, i couldn't find clear() method. So i am looping like below.

while(!q.empty())
    q.pop();

I got efficient algorithm for clearing queue at

http://stackoverflow.com/questions/709146/how-do-i-clear-the-stdqueue-efficiently

My question is: Why queue doesn't support clear() function ?

When deque and vector are supporting clear() method, what is the technical difficulty in supporting it for queue ?

Or is my above usecase very rare and hence not supported ? Thank you.

+2  A: 

queue is just an adapter for some underlying container, by default a deque, with restricted function (as you noted here). If you want the full blown function use the underlying deque instead of queue.

Steve Townsend
+7  A: 

According to http://www.cplusplus.com/reference/stl/queue/,

queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access it elements.

which means that the queue uses an already existing container, and is just really is an interface to this container as a FIFO queue.

This means queues are not meant to be cleared. If you need to clear a queue, this means you actually need to use an object that is not a queue, and therefore you should instead use the actual underlying container type, being a deque by default.

SirDarius
+1, Though, efficient clearing *is* possible, see my answer.
sellibitze
+7  A: 

Apart from what has been said already, you can clear a queue very easily:

queue<int> q;
...
q = queue<int>(); // Assign an empty queue
sellibitze