Why is it that when I call the same constructor, it works in one case, but not in the other?
std::vector<ulli> v(n);
for(int i = 0; i < n; i ){
inf >> v[i];
}
std::priority_queue<ulli> q1(std::greater<ulli>(), v); // fails
std::priority_queue<ulli> q2(std::less<ulli>(), v); // works
CodePudding user response:
Because of the default template parameter, the Compare of std::priority_queue<ulli> is of type std::less, and in your first example, you use std::greater to initialize std::less, which is not correct.
With help of CTAD, just
std::priority_queue q1(std::greater<ulli>(), v);
CodePudding user response:
As you can see from this page on cppreference, std::priority_queue<T> has two defaulted template parameters:
- one being its container type (
Container = std::vector<T>); - and the other being its comparator type (
Compare = std::less<T>).
So,
std::priority_queue<ulli>
indeed means
std::priority_queue<ulli, std::vector<ulli>, std::less<ulli>>
and provides no constructor that takes a std::greater<ulli> as comparator.
You should declare q1 as
std::priority_queue<ulli, std::vector<ulli>, std::greater<ulli>> q1(std::greater<ulli>(), v);
Or, if you're in C 17 (or newer), just:
std::priority_queue q1(std::greater<ulli>(), v);
