如何有效清除std :: queue? [英] How do I clear the std::queue efficiently?

查看:529
本文介绍了如何有效清除std :: queue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用std :: queue来实现JobQueue类。 (基本上,此类以FIFO方式处理每个作业)。
在一种情况下,我想一枪清除队列(从队列中删除所有作业)。
我在std :: queue类中看不到任何清除方法。

I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner). In one scenario, I want to clear the queue in one shot( delete all jobs from the queue). I don't see any clear method available in std::queue class.

如何有效地为JobQueue类实现清除方法?

How do I efficiently implement the clear method for JobQueue class ?

我有一个简单的循环弹出解决方案,但我正在寻找更好的方法。

I have one simple solution of popping in a loop but I am looking for better ways.

//Clears the job queue
void JobQueue ::clearJobs()
 {
  // I want to avoid pop in a loop
    while (!m_Queue.empty())
    {
        m_Queue.pop();
    }
}


推荐答案

A清除标准容器的常见习惯是与容器的空版本交换:

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 );
}

这也是清除某些容器内存储的内存的唯一方法( std :: vector)

It is also the only way of actually clearing the memory held inside some containers (std::vector)

这篇关于如何有效清除std :: queue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆