Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 867
pentix Avatar asked Jan 10 '23 15:01

pentix


1 Answers

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.

like image 104
Brian Bi Avatar answered Jan 21 '23 09:01

Brian Bi