The reason of using `std::greater` for creating min heap via `priority_queue`

The logical argument is as follows std::priority_queue is a container adaptor; basic memory considerations make the back the preferred place for modifications (with pop_back() and push_back()) for sequence containers such as std::vector. the priority_queue primitives are based on std::make_heap (constructor), std::pop_heap + container::pop_back (priority_queue::pop) and on container::push_back + std::push_heap (priority_queue::push) pop_heap will take the front … Read more

PriorityQueue not sorting on add

I guess you expect PriorityQueue to return elements in particular order when you iterate it. However, PriorityQueue doesn’t provide such a behaviour, because it’s implemented as a priority heap rather than sorted list. From javadoc: The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular … Read more

Why does PriorityQueue.toString return the wrong element order? [duplicate]

You need to poll the items from the PriorityQueue one by one. toString doesn’t do that. So instead of your System.out.println(queue); do this: while(!queue.isEmpty()) { System.out.println(queue.poll()); } The reason is that the PriorityQueue is never completely sorted internally, lookup how a heap works for more detail. Polling items from it fixes the heap during the … Read more

How do I use a PriorityQueue?

Use the constructor overload which takes a Comparator<? super E> comparator and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you’re not sure. (It’s pretty straightforward though.) … Read more