简体   繁体   中英

Iterating vector-based priority_queue

I need to iterate over std::vector -based priority_queue . As many answers here suggest, I can inherit from priority_queue and access underlying container ( std::vector in my case).

Is it guaranteed that priority_queue elements are stored starting from element 0 of the underlying vector and that vector size equals queue size?

PS. I am iterating regardless of priority, so I iterate: for (int i = 0; i < c.size(); ++i) ...

In short, yes.

The standard [priqueue.members] defines the operators on a priority queue in terms of push/emplace/pop_back and heap operations. It is trivial to see that the size of the underlying container will be equal to the size of the priority queue, and that elements will be stored starting from the beginning of the container.

In fact, the standard even guarantees that the underlying container will be a heap as defined by the standard make_heap algorithm.

That said, it is likely worth considering whether or not priority_queue is the best solution for your problem if iteration is required.

Yes.


As part of the container adaptor library, the job of priority_queue is to provide an extended/modified/limited interfaces of existing containers.

The underlying container is implemented as a protected member c . .size() is implemented in terms of return c.size() , and .top() is implemented in terms of return c.front() . [priqueue.overview]

Similarly, construction, push, and pop are effectively the same as using std::make_heap , push_heap , and pop_heap directly onto the underlying c . [priqueue.cons] , [priqueue.members]


More informations on ways to access the underlying c can be found here: Is there a way to access the underlying container of STL container adaptors?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM