How do I clear the std::queue efficiently?
A common idiom for clearing standard containers is swapping with an empty version of the container:
void clear( std::queue<int> &q )
{
std::queue<int> empty;
std::swap( q, empty );
}
It is also the only way of actually clearing the memory held inside some containers (std::vector)
Yes - a bit of a misfeature of the queue class, IMHO. This is what I do:
#include <queue>
using namespace std;;
int main() {
queue <int> q1;
// stuff
q1 = queue<int>();
}
Author of the topic asked how to clear the queue "efficiently", so I assume he wants better complexity than linear O(queue size). Methods served by David Rodriguez, anon have the same complexity:
according to STL reference, operator =
has complexity O(queue size).
IMHO it's because each element of queue is reserved separately and it isn't allocated in one big memory block, like in vector. So to clear all memory, we have to delete every element separately. So the straightest way to clear std::queue
is one line:
while(!Q.empty()) Q.pop();