0xpentix
0xpentix

Reputation: 742

Range based for-loop for priority_queue

Defining my priority_queue like this,

priority_queue<int> parts(start, start+N, less<int>());

the following code won't compile

for(int t : parts){
    ...
}

Which leads me to question:

In C++11, are range based for loops allowed for std::priority_queue?

In general, which structures are allowed to be iterated trough using a range based for-loop?

I know I can do pretty much the same thing like this:

while(!parts.empty()){
    cout << "Next element: " << parts.top() << endl;
    parts.pop();
}

Is it possible to iterate trough the queue nevertheless?

Upvotes: 5

Views: 2448

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

No, std::priority_queue does not support the range-based for loop.

The range-based for loop works on arrays and on classes that have begin() and end() member functions. This includes all containers in the C++ standard library as well as std::string (and its basic_string cousins) but not stacks, queues, or priority queues which are container adaptors and do not expose iterators.

Upvotes: 10

Related Questions