Answer the question
In order to leave comments, you need to log in
How to set priority queue with custom cmp?
In general, I searched on the Internet, but there are different implementations everywhere, and I don’t understand why something is written, so I turn to you for help, help, please.
Example:
priority_queue , cmp > min;
(why is there a vector in the declaration?, can cmp be written as
bool cmp(const int&a,const int&b){
return a<b;
}
Answer the question
In order to leave comments, you need to log in
Let's look at the documentation .
The std::priority_queue template has 3 parameters - element type, container and comparator.
priority_queue stores elements in a given container, maintains some kind of structure (heaps) there using the passed comparator for fast implementation of priority queue operations.
The default container is vector and the standard std::less comparator, so just priority_queue works, for example.
You may need to pass your own container if you want, for example, to change the allocator. Or you know that there will almost always be exactly K elements in the queue, and you pass some kind of container of your own, which immediately allocates K elements once.
However, if you only need to change the comparator (the third parameter), then you will also have to pass the second parameter. Well, the developers of the standard mixed up the order of the parameters. You cannot define a comparator without also defining a container. Therefore, it is necessary to write there vector<> in the second parameter.
Edit. The documentation also says that the comparator should return true if the first element is strictly less than the second. Your comparator example seems to be correct. However, note that the queue outputs the maximum element first. That is, if you need a minimum queue, then you need to change the sign in the comparator.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question