为什么我不能在成对的优先级队列中简单地覆盖 < ?

Why can't I simply overwrite < in a priority queue of pairs?

我知道我可以做 priority_queue < P, vector<P>, Compare > queue;,其中 Compare 是一个仿函数。但是因为默认的比较器是less<P>,和<是一样的,为什么当我执行下面的操作时它不起作用:

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 已经有一个 operator< declared inside namespace std.

因为它与 pair 在同一个命名空间中,std::less 会先找到那个,然后不再查找。

namespace std {
    bool operator<(const P& a, const P& b) {
        return (a.second < b.second);
    }
}

对我有用

更新: 为了安全起见,我们可以定义自己的类型:

class MyOwnPair: public std::pair<int,int>{};
typedef MyOwnPair P;

这是执行此操作的正确方法:

#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;
}