class Person { public: int age; };
I want to store objects of the class Person in a priority queue.
priority_queue< Person, vector<Person>, ??? >
I think I need to define a class for the comparison thing, but I am not sure about it.
Also, when we write,
priority_queue< int, vector<int>, greater<int> >
How does the greater work?
To create a priority queue, use one of the constructors. We can optionally pass the Comparator instance for custom ordering of the items. Notice the sequence of items in the priority queue is not always in sorted order, but when we retrieved the items then items are retrieved always in sorted order.
In C++, the STL priority_queue provides the functionality of a priority queue data structure. A priority queue is a special type of queue in which each element is associated with a priority value and elements are served based on their priority.
push() function is used to insert an element in the priority queue. The element is added to the priority queue container and the size of the queue is increased by 1. Firstly, the element is added at the back and at the same time the elements of the priority queue reorder themselves according to priority.
Use a priority_queue and another data structure support search i.e. binary search tree , hash . Here I use multimap . Maintain a priority_queue of Node and a multimap of Node at the same time. Then you can get data's pointer by key using multimap d .
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person
in this case. The default is to use std::less<T>
, which resolves to something equivalent to operator<
. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs) { return lhs.age < rhs.age; }
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>
. For example,
struct LessThanByAge { bool operator()(const Person& lhs, const Person& rhs) const { return lhs.age < rhs.age; } };
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
Concerning the use of std::greater<Person>
as comparator, this would use the equivalent of operator>
and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator>
that can operate on two Person
instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With