问题
I was looking through some STL documentation. I see that the syntax for a priority queue which stores in a descending order is:
std::priority_queue<int> q ;
//gives 9 8 7 6 5 4 3 2 1 when pushed and obtained
However, for storing in an ascending fashion, it's:
std::priority_queue< int, std::vector<int>, std::greater<int> > q ;
//gives 1 2 3 4 5 6 7 8 9 when pushed and obtained
I want to know what are the specific uses of the extra template parameters in the second example. As in, what does std::vector<int>
do in that example?
Also, can someone could further explain this declaration?
priority_queue< pair<int ,int > , vector< pair<int ,int > > , greater< pair<int ,int > > > q ;
回答1:
std::priority_queue is not a container in itself, it's a container adaptor, which means it uses another container internally to store the actual data in the queue.
By default it uses a std::vector
of the type stored in the queue.
The problem here is that just like passing arguments to a function with default arguments, you can't skip arguments in the template list even if they have default types, you must always provide the previous template arguments.
If you see the linked reference you will see that the second and third template arguments to std::priority_queue
have default types. If you want to change the third template argument you must also provide the second template argument as well, which is the actual underlying container. So for a std::priority_queue
of int
, you need to provide std::vector<int>
.
There are however a way to not pass the type of the comparator as a template argument, the std::priority_queue constructor also takes an (optional) argument for the comparator function. Here you can provide any function, function object, lambda or other callable object.
In your case you could do e.g.
std::priority_queue<int> q{std::greater<int>()};
The above declaration creates a std::greater<int>
object and passes it as comparator to the std::priority_queue
constructor.
回答2:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
std::priority_queue is a container which wraps another container, meaning that it only provide priority
and queue
abstraction on top of another container, as long this one match the SequenceContainer
concept.
A user may change containers if it want different time and memory complexity constraint. Or provide its own container.
the std::greater<T>
is a comparator on elements of type T
. It is required to satisfy total ordering.
来源:https://stackoverflow.com/questions/32440464/what-are-the-template-parameters-of-stdpriority-queue