How do I clear the std::queue efficiently?(如何有效地清除 std::queue?)
问题描述
我正在使用 std::queue 来实现 JobQueue 类.(基本上这个类以先进先出的方式处理每个作业).在一种情况下,我想一次性清除队列(从队列中删除所有作业).我在 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 类的 clear 方法?
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 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何有效地清除 std::queue?
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
