C++ 中,std::vector 是一个非常常用的动态数组容器。当存储的是自定义类对象时,可以使用 std::sort 搭配 lambda 表达式(推荐)、重载 < 运算符、使用自定义比较函数,对 std::vector 的自定义对象进行排序。lambda 表达式最为灵活、简洁,适合大多数排序需求。

1、使用 std::sort 和 Lambda 表达式

C++ 中,对存储自定义对象的 std::vector 进行排序,常用的方法是使用 std::sort搭配 Lambda 表达式来自定义排序逻辑。

#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Person {
    std::string name;
    int age;
};

int main() {
    std::vector<Person> people = {
        {"小明", 30}, {"张三", 25}, {"李四", 35}
    };

    std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
        return a.age < b.age;  // 按年龄升序排序
    });

    for (const auto& person : people) {
        std::cout << person.name << ": " << person.age << std::endl;
    }
}

2、定义 operator< 运算符

C++ 中,要对 std::vector 中的自定义对象进行排序,可以通过为该类定义 operator< 运算符。std::sort 默认使用 < 运算符进行比较。

#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 自定义类
class Person {
public:
    std::string name;
    int age;

    Person(std::string n, int a) : name(n), age(a) {}

    // 定义 operator<,按年龄排序
    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {
        Person("小明", 30),
        Person("张三", 25),
        Person("李四", 35)
    };

    std::sort(people.begin(), people.end());  // 使用 operator< 进行排序

    for (const auto& p : people) {
        std::cout << p.name << ": " << p.age << std::endl;
    }

    return 0;
}

3、使用自定义比较函数

C++ 中,可以使用 std::sortstd::vector 中的自定义对象进行排序,关键在于提供一个自定义比较函数或Lambda 表达式。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;



struct Person {
    std::string name;
    int age;
};

// 自定义比较函数(按 age 升序)
bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;
}

int main() {
    std::vector<Person> people = {
        {"小明", 30},
        {"张三", 25},
        {"李四", 35}
    };

    std::sort(people.begin(), people.end(), compareByAge);

    for (const auto& person : people) {
        std::cout << person.name << ": " << person.age << std::endl;
    }

    return 0;
}

推荐文档