我使用std::queue实现JobQueue类。(基本上这个类以FIFO方式处理每个作业)。
在一个场景中,我希望一次性清除队列(从队列中删除所有作业)。
我在std::queue类中没有看到任何可用的清除方法。
如何有效地实现JobQueue类的清除方法?
我有一个简单的解决方案弹出在一个循环,但我正在寻找更好的方法。
//Clears the job queue
void JobQueue ::clearJobs()
{
// I want to avoid pop in a loop
while (!m_Queue.empty())
{
m_Queue.pop();
}
}
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();
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();