Hello, I have a the following priority_queue: priority_queue<pair<int,
string> > pq;
AFAICT, priority_queues doesn't support iterators. My question: is
there a way to print its contents without emptying it?
Right now I'm using the following code:
while (!pq.empty())
{
cout << setw(3) << pq.top().first << ": " << pq.top().second <<
endl;
pq.pop();
}
I also ran into this some time ago and decided that it was better for
me to use a normal vector and sort it before starting to retrieve
elements. This was actually faster than inserting the elements into
the priority_queue and then retrieving them since insertion was O(1)
for the vector. This option might not be available for you if you do
not first insert all the elements and later only extracts.
What you can do is to use the the fact that you can specify the
container in the constructor, something like:
std::vector base;
std:
riority_queue(std::less(), base) queue;
Then push()/pop() from the queue but iterate over base. Be aware that
if you make any changes to base you should run std::make_heap() on it.
You might have guessed by now that priority_queue is just a wrapper
that uses make_heap(), pop_heap() and push_heap() on a underlying
container, which is why it's called an adaptor and not a container.
[pjp] Nope. This constructor uses base to *initialize* the protected
member c, which is of type container_type, not container_type&. So
any changes to the priority_queue are *not* reflected in base.