关于在优先队列使用匿名函数的问题

  1. https://www.cnblogs.com/64open/p/5267678.html
  2. 在priority_queue中使用匿名函数的正确姿势:
bool cmp(const pair<int,int>& a, const pair<int,int>& b){return a.first + a.second > b.first + b.second;}
class Solution {
struct mycompare{
    bool operator()(pair<int,int>& a, pair<int,int>& b){
        return a.first + a.second > b.first + b.second;
    }
};
public:
    vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
        int sz1 = nums1.size();
        int sz2 = nums2.size();
        // priority_queue<Node, vector<Node>, cmp> q;
        // priority_queue<pair<int,int>, vector<pair<int, int>>, mycompare> pq;
        auto cmp2 = [](const pair<int,int>& a, const pair<int,int>& b){return a.first + a.second > b.first + b.second;};
        priority_queue<pair<int,int>, vector<pair<int, int>>, decltype(cmp2)> pq(cmp2);
        for(auto a : nums1) for(auto b : nums2) pq.push({a, b});
        vector<pair<int, int>> ret;
        while(!pq.empty() && int(ret.size()) < k){
            ret.push_back(pq.top());
            pq.pop();
        }
        // -------------------------test-------------------------------
        // vector<int> test = {1,3,4,2,5,6,4,3,6,4,6,7,4,7,3};
        // // sort(test.begin(), test.end(), [](int a, int b){return a > b;});
        // sort(test.begin(), test.end(), cmp);
        // for(auto a : test) cout<<a<<' ';
        // -------------------------test-------------------------------
        return ret;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。