跳到正文

算法·理论

优先队列解释文章

the_Wolf_King约 9 分钟
原文
文章信息与版本

文章信息

发布
2025年8月1日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 9 分钟

版本

  1. v1当前

C++优先队列存储pair的简洁实现指南

下面是各种定义pair优先队列的简洁实现方法,使用简短的名称并保持清晰注释:

C++
#include <iostream>
#include <queue>
#include <vector>
#include <functional> 
using namespace std;

int main() {
    // 方法1:默认比较(大顶堆,按first排序)
    priority_queue<pair<int, string>> pq1;  // first大的优先
    
    // 方法2:小顶堆(按first排序)
    // 使用greater: first小的优先
    priority_queue<pair<int, string>, vector<pair<int, string>>, greater<>> pq2;
    
    // 方法3:函数对象(按second长度排序)
    struct CmpLen {  // 名称简洁
        bool operator()(const auto& a, const auto& b) const {
            return a.second.length() > b.second.length(); // 短字符串优先
        }
    };
    priority_queue<pair<int, string>, vector<pair<int, string>>, CmpLen> pq3;
    
    // 方法4:Lambda表达式(按first升序)
    auto cmp = [](const auto& a, const auto& b) { 
        return a.first > b.first;  // 小顶堆
    };
    priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(cmp)> pq4(cmp);
    
    // 方法5:函数指针(按first降序)
    bool fcmp(const auto& a, const auto& b) { // 函数名简洁
        return a.first < b.first;  // 大顶堆
    };
    priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(&fcmp)> pq5(fcmp);
    
    // 方法6:多级排序(先first降序,再second长度升序)
    struct MultiCmp {  // 名称简洁
        bool operator()(const auto& a, const auto& b) const {
            if (a.first != b.first) 
                return a.first < b.first;  // first大的优先
            return a.second.length() > b.second.length(); // 长度短的优先
        }
    };
    priority_queue<pair<int, string>, vector<pair<int, string>>, MultiCmp> pq6;
    
    // ===== 使用示例 =====
    // 填充数据到pq6
    pq6.push({3, "Fox"});
    pq6.push({3, "Elephant"});
    pq6.push({1, "Cat"});
    pq6.push({2, "Bird"});
    pq6.push({3, "Ant"});
    
    cout << "多级排序结果:\n";
    while (!pq6.empty()) {
        auto [num, str] = pq6.top();  // C++17结构化绑定
        cout << num << " - " << str << " (len:" << str.length() << ")\n";
        pq6.pop();
    }
    /* 输出:
        3 - Ant (len:3)
        3 - Fox (len:3)
        3 - Elephant (len:8)
        2 - Bird (len:4)
        1 - Cat (len:3)
    */
    
    return 0;
}

简洁命名对照表

方法推荐名称说明
默认比较无需命名直接使用priority_queue
函数对象CmpXxx如CmpLen, CmpVal
Lambda比较器cmp简短通用
函数指针fcmpf表示function
多级排序MultiCmp表达多条件比较
优先队列实例pqX如pq1, pq2

各方法核心要点

  1. 默认比较

    C++
    priority_queue<pair<int, string>> pq;
    • 最大堆(堆顶元素first最大)
    • 相同first时按second字典序
  2. 使用greater

    C++
    priority_queue<pair<int, string>, vector<pair<int, string>>, greater<>> pq;
    • 最小堆(堆顶元素first最小)
    • C++14后可用greater<>自动推导类型
  3. 函数对象

    C++
    struct CmpRule {  // 规则名
        bool operator()(const auto& a, const auto& b) const {
            // 返回true表示a优先级低于b
            return 比较表达式; 
        }
    };
    • 推荐使用auto简化模板参数
    • 必须包含const和引用
  4. Lambda表达式

    C++
    auto cmp = [](const auto& a, const auto& b) { ... };
    priority_queue<..., decltype(cmp)> pq(cmp);
    • C++14支持泛型Lambda
    • 声明时需同时指定比较器类型和实例
  5. 函数指针

    C++
    bool fcmp(const auto& a, const auto& b) { ... }
    priority_queue<..., decltype(&fcmp)> pq(fcmp);
    • 适合需要动态切换比较规则的场景
    • 效率略低于函数对象
  6. 多级排序

    C++
    struct MultiCmp {
        bool operator()(const auto& a, const auto& b) const {
            // 第一条件
            if (a.key1 != b.key1) 
                return ...;
                
            // 第二条件
            if (a.key2 != b.key2)
                return ...;
                
            // 更多条件...
            return ...;
        }
    };
    • 按优先级顺序逐级比较
    • 确保每个条件都满足严格弱序

最佳实践建议

  1. 命名原则

    • 结构体:Cmp + 特征(如CmpLen)
    • 函数:fcmp + 特征(如fcmpDesc)
    • Lambda:cmp + 特征(如cmpAsc)
    • 实例:pq + 数字(如pq1)
  2. 类型简化技巧

    C++
    // 使用using简化复杂类型
    using IntStrPair = pair<int, string>;
    priority_queue<IntStrPair> pq;
    
    // C++17自动模板推导
    priority_queue pq{greater{}, vector<IntStrPair>{}};
  3. 常用比较模式

    C++
    // 大顶堆(降序)
    return a.value < b.value;
    
    // 小顶堆(升序)
    return a.value > b.value;
    
    // 多条件排序
    if (a.pri != b.pri) 
        return a.pri < b.pri; // 高优先级在前
    return a.time > b.time;   // 早时间在前
  4. 性能优化

    • 对于大型对象:始终使用const auto&
    • 频繁使用的比较器:用函数对象替代Lambda
    • 避免在比较函数中调用复杂计算

这些简洁实现方法覆盖了优先队列处理pair的所有常见场景,平衡了代码简洁性和可读性,适合实际开发使用。

原文