c++怎么对自定义对象使用std::sort_c++自定义排序规则与比较函数示例

在C++中对自定义对象使用std::sort需提供排序规则,可通过重载

在C++中对自定义对象使用 std::sort,需要提供排序规则。可以通过重载操作符、定义比较函数或使用lambda表达式来实现。

1. 通过重载操作符

如果类中定义了操作符,std::sort可以直接使用。

示例:

假设有一个表示学生的类:

struct Student {
    std::string name;
    int score;

    // 重载 < 操作符,按成绩升序
    bool operator<(const Student& other) const {
        return score < other.score;
    }
};

使用std::sort

std::vector students = {{"Alice", 85}, {"Bob", 72}, {"Charlie", 90}};
std::sort(students.begin(), students.end());

排序后,students 按 score 升序排列。

2. 使用自定义比较函数

可以传入一个函数指针或函数对象作为比较规则。

示例:按姓名升序排序
bool compareByName(const Student& a, const Student& b) {
    return a.name < b.name;
}

调用方式:

std::sort(students.begin(), students.end(), compareByName);

3. 使用Lambda表达式(推荐)

Lambda更灵活,适合临时定义排序逻辑。

示例:按成绩降序排序
std::sort(students.begin(), students.end(), 
          [](const Student& a, const Student& b) {
              return a.score > b.score;
          });
示例:先按成绩降序,成绩相同时按姓名升序
std::sort(students.begin(), students.end(),
          [](const Student& a, const Student& b) {
              if (a.score != b.score)
                  return a.score > b.score;
              return a.name < b.name;
          });

4. 注意事项

比较函数必须满足“严格弱序”规则:

  • 不能有 a
  • 如果 a
  • 如果 a

否则可能导致程序崩溃或未定义行为。

基本上就这些。根据需求选择合适的方式,lambda最常用也最清晰。