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;
    }
  • 相关阅读:
    Luogu P3275 糖果
    Python基础学习
    SharePoint 2013
    Office
    KnockoutJS
    SharePoint 2013
    Bootstrap
    SharePoint 2013
    CSS
    AngularJS
  • 原文地址:https://www.cnblogs.com/kinsang/p/9961403.html
Copyright © 2011-2022 走看看