English 中文(简体)
为什么std::queue不支持clear()函数?
原标题:Why doesn t std::queue support a clear() function?

我有一个要求:对于一个函数,我得到的输入是一个数字流。我的意思是,该函数在每次调用中都使用一个号码。我使用std::queue来存储数字流。只有当满足某些条件时,我才需要处理收集的一组数字。如果条件不满足,我需要将所有元素放入队列,然后开始在其中存储新的数字。为了清空队列,我找不到clear()方法。所以我循环如下:

while(!q.empty())
    q.pop();

我得到了一个有效的算法来清除std::queue

如何有效地清除std::队列

我的问题是:为什么std::queue不支持clear()函数?

由于std::dequetd::vector都支持clear()方法,因此为std::queue支持它的技术难点是什么?

还是我上面的用例非常罕见,因此不受支持?

最佳回答

根据http://www.cplusplus.com/reference/stl/queue/中,

队列被实现为容器适配器,容器适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问it元素。

这意味着队列使用一个已经存在的容器,并且实际上是作为FIFO队列的这个容器的接口。

这意味着队列不会被清除。如果您需要清除队列,这意味着您实际上需要使用一个不是队列的对象,因此您应该使用实际的底层容器类型,默认情况下是deque。

问题回答

除了已经说过的以外,您可以非常容易地清除队列:

queue<int> q;
...
q = queue<int>(); // Assign an empty queue

或在C++11中

q = {};

queue只是一些底层容器的适配器,默认情况下是一个deque,具有受限功能(如您在此处所述)。如果您想要完整的函数,请使用底层的deque,而不是queue

将此添加到我不断增加的使STL可读的函数列表中:

template <typename T> 
void Clear(std::queue<T>& Queue) 
{
    Queue = std::queue<T>(); // Assign to empty queue
}

这只是sellibitze优秀答案的包装,但意味着我不必每次使用该技巧时都添加评论。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签