C++如何自定义vector的排序函数_C++容器排序与自定义比较方法

C++中对vector自定义排序需提供比较函数,常用方法包括:1. 函数对象重载operator()实现升序比较;2. Lambda表达式简洁实现按成绩或名字长度排序;3. 普通函数传参方式;4. 调整比较条件实现降序。关键满足严格弱序要求。

c++如何自定义vector的排序函数_c++容器排序与自定义比较方法

在C++中对vector进行排序,通常使用std::sort函数。当vector中的元素是自定义类型(如结构体、类)或需要特殊排序规则时,就需要提供自定义的比较函数。以下是几种常见的实现方式。

1. 使用函数对象(仿函数)

定义一个函数对象,重载operator(),用于比较两个元素。

例如,对包含学生信息的vector按成绩升序排序:

#include <vector>
#include <algorithm>
#include <iostream>

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

struct CompareByScore {
    bool operator()(const Student& a, const Student& b) const {
        return a.score < b.score;  // 升序
    }
};

int main() {
    std::vector<Student> students = {{"Alice", 85}, {"Bob", 72}, {"Charlie", 90}};
    
    std::sort(students.begin(), students.end(), CompareByScore{});
    
    for (const auto& s : students) {
        std::cout << s.name << ": " << s.score << "\n";
    }
    return 0;
}

2. 使用Lambda表达式

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) {
        return a.name.size() < b.name.size();
    });

3. 使用普通函数

也可以定义独立的比较函数,传给sort

Bardeen AI Bardeen AI

使用AI自动执行人工任务

Bardeen AI 165 查看详情 Bardeen AI
bool compareByName(const Student& a, const Student& b) {
    return a.name < b.name;
}

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

注意:函数必须接受两个const引用参数,返回bool值。

4. 逆序排序

若要降序排列,只需调整比较条件。

std::sort(students.begin(), students.end(), 
    [](const Student& a, const Student& b) {
        return a.score > b.score;  // 降序
    });

或者使用std::greater配合基础类型,但自定义类型仍需手动指定逻辑。

掌握这些方法后,就能灵活控制vector中任意类型的排序行为。关键是确保比较函数满足“严格弱序”:即对于任意a、b,不能同时满足comp(a,b)和comp(b,a),且具有可传递性。

基本上就这些,不复杂但容易忽略细节。

以上就是C++如何自定义vector的排序函数_C++容器排序与自定义比较方法的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。