I created a lambda comp according to what I use in vectors, but it doesn't work, I would like to know why it doesn't work and how to do it properly.
CODE:
auto cmp=[](const std::pair<int,int>& a,const std::pair<int,int>& b){
return (b.first>a.first)||(b.second>a.second);
};
std::priority_queue<std::pair<int,int>,std::vector<std::pair<int,int>>,decltype(cmp)> q(cmp);
CodePudding user response:
As you mentioned in the comments: std::greater<std::pair<int, int>>
works just fine, and yours not working because the comparison equation isn't 'strict enough' - right.
Lets take two pairs p1 = (3,5) and p2 = (4,2), if we comapre p1 and p2 according to your function, it will output cmp(p1, p2) = true
because of b.first > a.first // 4 > 3
.
Also, if we compare p2 and p1 the same way(the only difference is the order of p1 and p2), it will output cmp(p2, p1) = true
because of b.second > a.second // 5 > 2
.
Not saying anything, when a == b
, if we compare some pair to itself it will be false
.
So the compiler has to have problems while comparing the same pairs one more time, but this time with the reverse order.
Since the question doesn't contain many details about how you use the queue, the problem has to be this. That's why greater
working and not this one.
If you want to make work yours, you should try a more specific and strict equation, try to use the &&
operator instead of ||
and consider the equal variant too.
Hope it helps, I had similar problems a few years ago, while I was trying to sort vector of pairs by my way.