C++ 遍历 std 队列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2950501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating through std queue
提问by Max Frai
I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error:
我正在尝试使用 BOOST_FOREACH 来遍历 std::queue。但是那个类中没有迭代器,因为我有一个错误:
std::queue<std::string> someList;
BOOST_FOREACH(std::string temp, someList)
{
std::cout << temp;
}
>no matching function for call to begin(...)
>no type named ‘iterator' in ‘class std::queue<std::basic_string<char> >'
I need in structure like: the first comes, the first goes away.
我需要这样的结构:先来,先走。
回答by Michael Kristofik
std::deque
supports efficient insert and removal at the beginning and end of the data structure. You can do queue operations manually using push_back
and pop_front
.
std::deque
支持在数据结构的开头和结尾进行高效的插入和删除。您可以使用push_back
和手动执行队列操作pop_front
。
A queue uses a deque internally by default. It's a wrapper that only exposes queue operations (hence why you can't iterate over it). I asked a similar questiona while back, and the best answer gave me good insight into the real use of std::queue
. One should use std::queue
not because one needs a queue, but to make it clear that only queue-like operations are legal on a given data structure. It sounds like you need more freedom than that, so go with deque, list, or some other structure with O(1) insert and remove at both ends.
默认情况下,队列在内部使用双端队列。它是一个仅公开队列操作的包装器(因此您不能对其进行迭代)。不久前我问了一个类似的问题,最佳答案让我对std::queue
. std::queue
不应该因为需要队列而使用它,而是要清楚地表明,对于给定的数据结构,只有类似队列的操作才是合法的。听起来您需要比这更多的自由,所以使用双端队列、列表或其他一些在两端都具有 O(1) 插入和删除的结构。
回答by chub
you can use std::list with push_front and pop_back
您可以将 std::list 与 push_front 和 pop_back 一起使用
回答by pmr
std::queue
is a container adaptor. It uses std::deque
as the default underlying container. Access to this container isn't possible and thus isn't iteration in any way.
std::queue
是一个容器适配器。它std::deque
用作默认的底层容器。无法访问此容器,因此不会以任何方式进行迭代。
The best way is to use a std::deque
or std::list
and manage the queue behaviour yourself. Possibly provide your own wrapper around it.
最好的方法是使用std::deque
orstd::list
并自己管理队列行为。可能在它周围提供您自己的包装器。