admin管理员组

文章数量:1624351

优先队列,比较pair元素,实现按第一个值降序,第一个值相同,按第二个值升序。
其它情况均可通过修改cmp类实现。

struct cmp {
    bool operator()(pair<int,int>& a, pair<int,int>& b) {
        if (a.first == b.first)
            return a.second > b.second;
        else
            return a.first < b.first;
    }
};

int main()
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
    pq.push({2, 3});
    pq.push({2, 4});
    pq.push({2, 2});
    pq.push({4, 2});
    while (!pq.empty()) {
        cout << pq.top().first << " " << pq.top().second << endl;
        pq.pop();
    }
    vector<int> nums{2, 4, 2, 13, 5};
    sort(nums.begin(), nums.end(), [](int a, int b) {
        return a < b;
    });
    for (auto n : nums)
        cout << n << endl;
    return 0;
}

结果:

4 2
2 2
2 3
2 4

本文标签: 自定义函数priorityqueue