C++ 使用STL时自定义比较函数cmp

以priority_queue的用法为例
方法一

********************************方法一
struct Node {
    int x,y;
    bool operator <(Node a) const  {    //必须加const
        return y < a.y;
    }
    bool operator >(Node a) const  {    //必须加const
        return y > a.y;
    }
};
//  priority_queue A;   //默认  大根堆
priority_queuevector, less>A;    //大根堆
priority_queuevector, greater > B;    //小根堆

类似方法一

********************************类似方式法一
struct Node {
    int x;
    int y;
    friend  bool operator<(const Node &a,const Node &b) {
        return  a.x < b.x;  //大顶堆
    }
    friend  bool operator>(const Node &a,const Node &b) {
        return  a.x > b.x;  //小顶堆
    }
};

priority_queue A;   //默认  大根堆
priority_queuevector, greater > B;    //小根堆

方法二

********************************方法二:
struct Node {
    int x;
    int y;
};

bool operator<(const Node &a, const Node &b) {
    return a.x//大顶堆
}

bool operator>(const Node &a, const Node &b) {
    return a.x>b.x;         //小顶堆
}

priority_queuevector,less > A;    //大根堆
priority_queuevector, greater > B;    //小根堆

方法三

//********************************方法三:
struct Node {
    int x;
    int y;
};

struct cmp {
    bool operator()(Node a,Node b) {
        return  a.x > b.x;  //小顶堆
    }
};

struct cmp1 {
    bool operator()(Node a,Node b) {
        return  a.x < b.x;  //大顶堆
    }
};

priority_queuevector,cmp1 > A;      //大根堆
priority_queuevector, cmp > B;    //小根堆

队列节点是指针

//当队列节点是指针时,用法不同
struct Node {
    int x;
    int y;
};
struct cmp {
    bool operator () (Node const *n1, Node const *n2) {
        return n1->xx;     //大顶推
    }
};
struct cmp1 {
    bool operator () (Node const *n1, Node const *n2) {
        return n1->x>n2->x;     //小顶推
    }
};

priority_queuevector, cmp > A;   //大根堆
priority_queuevector, cmp1 > B;  //小根堆

统一测试

ostream & operator <<(ostream &out,const struct Node& n) {
    out<<"n.x="<"    n.y="<return out;
}

const vectortn= {{1,1},{2,2},{3,3},{4,4},{5,5}};

void test() {
    for (auto &a:tn) {
        A.push(a);
        B.push(a);
    }

    cout<<"A:"<while(!A.empty()) {
        cout<cout<<"B:"<while(!B.empty()) {
        cout<int main() {
    test();
    return 0;
}

你可能感兴趣的:(C/C++,(Accumulate))