zoukankan      html  css  js  c++  java
  • C++ 自定义结构体的Priority Queue

    比较函数return true 意味着排序需要交换。

    #include <iostream>
    #include <queue>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    struct Item {
        int val = 0;
        int idx = 0;
    };
    
    /**
     * want ascending order, if ties, prefer less idx
     * return true if we want swap happen
     *
     */
    class Compare {
    public:
        bool operator() (const Item &lhs, const Item &rhs) {
            if (lhs.val == rhs.val) {
                return lhs.idx > rhs.idx;
            }
            return lhs.val < rhs.val;
        }
    };
    
    int main() {
        Item item1;
        item1.val = 1;
        item1.idx = 1;
        Item item2;
        item2.val = 2;
        item2.idx = 2;
        vector<Item> v = {item1, item2};
        priority_queue<Item, vector<Item>, Compare> myPQ(v.begin(),v.end());
        cout << myPQ.top().idx << endl;
        std::sort(v.begin(),v.end(), Compare());
        cout << v[0].val << endl;
        return 0;
    }
  • 相关阅读:
    java多线程实例
    Python——文件操作
    Python—— *与** 参数说明
    Python——序列
    多元线性回归
    Gson转换时,Double转式化
    ftp上传下载
    发送邮件
    jsonp的使用
    用CSS3和Canvas来画网格
  • 原文地址:https://www.cnblogs.com/kinsang/p/9961403.html
Copyright © 2011-2022 走看看