I'm aware that I can just do priority_queue < P, vector<P>, Compare > queue;
, where Compare
is a functor. But since the default comparator is less<P>
, and it is the same as <
, why doesn't it work when I do the following:
typedef pair<int, int> P;
bool operator<(const P& a, const P& b){
return (a.second < b.second);
}
int main(int argc, char const *argv[]){
int vec[] = {3, 6, 7, 8, 1, 2}; // just for testing
priority_queue <P> queue;
for(int i = 0; i < 6; ++i){
queue.push(make_pair(i, vec[i]));
}
cout << queue.top().second << endl; // returns 2
return 0;
}
std::pair
already has an operator<
declared inside namespace std .
As this is in the same namespace as pair
, std::less
will find that one first and then not look any further.
This is the correct way to do this:
#include <utility>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
typedef pair<int, int> P;
struct comp {
bool operator()(const P& a, const P& b){
return (a.second < b.second);
}
};
int main(int argc, char const *argv[]){
int vec[] = {3, 6, 7, 8, 1, 2}; // just for testing
priority_queue <P, std::vector<P>, comp> queue;
for(int i = 0; i < 6; ++i){
queue.push(make_pair(i, vec[i]));
}
cout << queue.top().second << endl; // returns 2
return 0;
}
namespace std {
bool operator<(const P& a, const P& b) {
return (a.second < b.second);
}
}
and it work for me
UPD: We can define own type for safeness:
class MyOwnPair: public std::pair<int,int>{};
typedef MyOwnPair P;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.