基于范围的for循环用于priority_queue

pen*_*tix 3 c++ for-loop priority-queue c++11

像这样定义我的priority_queue,

priority_queue<int> parts(start, start+N, less<int>());
Run Code Online (Sandbox Code Playgroud)

以下代码将无法编译

for(int t : parts){
    ...
}
Run Code Online (Sandbox Code Playgroud)

这引出了我的问题:

在C++ 11中,是否允许基于范围的循环 std::priority_queue

通常,允许使用基于范围的for循环迭代哪些结构?

我知道我可以做同样的事情:

while(!parts.empty()){
    cout << "Next element: " << parts.top() << endl;
    parts.pop();
}
Run Code Online (Sandbox Code Playgroud)

是否可以通过队列进行迭代?

Bri*_*ian 7

不,std::priority_queue不支持基于范围的for循环.

基于范围的for循环适用于数组以及具有begin()end()成员函数的类.这包括C++标准库中的所有容器以及std::string(及其basic_string表兄弟),但不包括作为容器适配器的堆栈,队列或优先级队列,并且不公开迭代器.

  • @pentix:如果你想要`std :: priority_queue`的行为和性能,以及迭代的能力,你可以使用一个向量和堆操作,[`make_heap`](http://en.cppreference. com/w/cpp/algorithm/make_heap),[`push_heap`](http://en.cppreference.com/w/cpp/algorithm/push_heap)和[`pop_heap`](http://en.cppreference. COM/W/CPP /算法/ pop_heap).实际上,这正是`std :: priority_queue`的实现方式. (2认同)