You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建按首个元素升序存储整数对的优先队列?

实现按首个整数值升序排列的pair优先队列

当然可以啦!C++标准库的priority_queue其实提供了灵活的排序规则定制方式,刚好能解决你的问题~

首先得说清楚为什么你当前的代码会是降序:priority_queue默认是大顶堆,使用的比较器是less<T>。对于pair<int, int>来说,它的比较逻辑是先比第一个元素,第一个元素大的优先级更高;如果第一个元素相同,再比第二个元素。所以你的代码会把30 10放在队列最前面,呈现降序排列。

下面给你两种实用的解决方案:

方法一:用内置的greater比较器直接实现升序

直接在声明priority_queue时,指定使用greater<pair<int, int>>作为比较器,同时需要显式指定底层容器(通常用vector)。这样队列就会变成小顶堆,完全符合你要的首个元素升序的需求。

示例代码:

#include <queue>
#include <vector>
#include <iostream>

using namespace std;

int main() {
    int n = 5;
    // 声明按pair首元素升序排列的优先队列
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> queue;
    
    int t, d;
    for(int i=0; i<n; i++){
        cin>>t>>d;
        queue.push(make_pair(t, d));
    }
    
    // 验证输出:会按0 10、0 10、1 10、2 10、30 10的顺序弹出
    while(!queue.empty()){
        auto top = queue.top();
        cout << top.first << " " << top.second << endl;
        queue.pop();
    }
    return 0;
}

这种方法适合你只需要按pair默认升序规则(先首元素升序,再次元素升序)的场景,简单直接,不需要额外写自定义逻辑。

方法二:自定义比较器实现更灵活的排序

如果之后你需要更个性化的排序规则(比如首元素相同时,按次元素降序排列),可以自定义一个比较结构体,重载()运算符来实现自己的排序逻辑。

比如我们要实现“首元素升序,首元素相同时次元素降序”的规则,代码可以这样写:

#include <queue>
#include <vector>
#include <iostream>

using namespace std;

// 自定义比较器结构体
struct PairCompare {
    bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
        // 规则:如果a的首元素比b大,a优先级更低(排后面)
        // 首元素相同时,a的次元素比b小,a优先级更低(排后面)
        if (a.first != b.first) {
            return a.first > b.first;
        } else {
            return a.second < b.second;
        }
    }
};

int main() {
    int n = 5;
    priority_queue<pair<int, int>, vector<pair<int, int>>, PairCompare> queue;
    
    int t, d;
    for(int i=0; i<n; i++){
        cin>>t>>d;
        queue.push(make_pair(t, d));
    }
    
    // 验证输出:首元素相同的情况下,次元素大的会先弹出
    while(!queue.empty()){
        auto top = queue.top();
        cout << top.first << " " << top.second << endl;
        queue.pop();
    }
    return 0;
}

小提醒

自定义比较器的逻辑要注意:operator()返回true时,表示参数a的优先级低于b,会被放在队列的后面。所以要根据你想要的排序顺序,写出对应的判断条件。

内容的提问来源于stack exchange,提问作者user16776319

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:32:50