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?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01