具有自定义比较器运算符重载的c ++优先级队列

Pro*_*Cpp 1 c++

为什么我不能在同一结构中重载比较器运算符?

在同一结构中重载运算符时出现此错误。但是,在单独的结构中定义运算符是可行的 https://ideone.com/VVHb1L

 
struct myC {
    int i;
    myC(int x){
        this -> i = x;
    }
    // this is syntactically wrong
    // bool operator()(myC &a, myC &b) {
    //  return a.i < b.i;
    // }
 
    bool operator()(myC &b) {
        return this ->i < b.i;
    }
};


int main() {
    // your code goes here
    priority_queue<myC, vector<myC>, myC> q;
    q.push(myC(10));
    q.pop();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:基于@Homer512的输入,operator()不是比较器运算符。它是一个函数调用运算符。

Jer*_*fin 8

如果要在同一结构中进行重载,通常会重载operator<而不是operator(). 当然,您需要使其const正确。

struct myC {
    int i;
    myC(int x){
        this -> i = x;
    }
 
    bool operator<(myC const &b) const {
        return this ->i < b.i;
    }
};
Run Code Online (Sandbox Code Playgroud)

当您重载 时operator<,默认情况下将使用它 - 您不需要指定比较器参数:

priority_queue<myC, vector<myC>> q;
Run Code Online (Sandbox Code Playgroud)

  • @CaptainGiraffe:它确实意味着存在自然的顺序 - 但如果该顺序对于该结构/类来说不自然,那么在任何情况下它都可能不应该是类成员。 (3认同)