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::sort
对 std::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; }