导航

C++比较函数

Posted on 2025-07-18 16:13  Zyeah  阅读(42)  评论(0)    收藏  举报

一、标准库内置比较函数

头文件
image

二、自定义比较函数

  1. 函数对象(仿函数)
    通过重载 operator() 定义比较逻辑:
struct Student {
    std::string name;
    int score;
};

// 按分数升序排序
struct CompareByScore {
    bool operator()(const Student& a, const Student& b) const {
        return a.score < b.score;
    }
};
std::priority_queue<Student, std::vector<Student>, CompareByScore> pq;
  1. Lambda 表达式
    直接在算法中定义匿名比较规则(C++11 起支持):
std::vector<Student> students = {{"Alice", 90}, {"Bob", 85}};

// 按分数降序排序
std::sort(students.begin(), students.end(), 
    [](const Student& a, const Student& b) {
        return a.score > b.score;
    });
  1. 普通函数指针
    将普通函数作为比较器传递:
bool compareByScore(const Student& a, const Student& b) {
    return a.score < b.score;
}

std::sort(students.begin(), students.end(), compareByScore);
  1. 为自定义类型重载 operator< 以支持默认比较:
struct Student {
    std::string name;
    int score;
    
    // 默认按分数升序排序
    bool operator<(const Student& other) const {
        return score < other.score;
    }
};