一、标准库内置比较函数
头文件

二、自定义比较函数
- 函数对象(仿函数)
通过重载 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;
- 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;
});
- 普通函数指针
将普通函数作为比较器传递:
bool compareByScore(const Student& a, const Student& b) {
return a.score < b.score;
}
std::sort(students.begin(), students.end(), compareByScore);
- 为自定义类型重载 operator< 以支持默认比较:
struct Student {
std::string name;
int score;
// 默认按分数升序排序
bool operator<(const Student& other) const {
return score < other.score;
}
};
浙公网安备 33010602011771号