目录
使用普通函数(函数指针)
对于常见的数据类型,可以传递一个普通的函数来进行自定义排序,接受两个元素并返回一个比较结果,通常返回 true
表示第一个元素小于第二个元素
#include <iostream>
#include <vector>
#include <algorithm>
bool customCompare(int a, int b) {
return a < b; // 升序排序
}
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3};
// 使用自定义比较函数排序
std::sort(vec.begin(), vec.end(), customCompare);
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
使用 Lambda 表达式
C++11 引入了 Lambda 表达式,对于常见的数据类型,可以直接在 sort
调用中定义排序规则
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3};
// 使用 Lambda 表达式进行升序排序
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a < b; // 升序排序
});
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
使用函数对象(仿函数)
可以定义一个函数对象(即一个重载了 operator()
的类或结构体)来作为排序的比较器
#include <iostream>
#include <vector>
#include <algorithm>
class CustomCompare {
public:
bool operator()(int a, int b) {
return a > b; // 降序排序
}
};
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3};
// 使用函数对象进行降序排序
std::sort(vec.begin(), vec.end(), CustomCompare());
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
自定义结构体(自定义类)排序
对于数据类型是自定义的结构体或者是自定义的类,可以使用自定义函数排序或者lambda表达式
自定义函数排序
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
Person(std::string name, int age) : name(name), age(age) {}
};
bool compareByAge(const Person& a, const Person& b) {
return a.age < b.age; // 按年龄升序排序
}
int main() {
std::vector<Person> people = {
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
};
// 使用自定义的比较函数排序
std::sort(people.begin(), people.end(), compareByAge);
for (const auto& person : people) {
std::cout << person.name << ": " << person.age << std::endl;
}
return 0;
}
lambda表达式
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
Person(std::string name, int age) : name(name), age(age) {}
};
int main() {
std::vector<Person> people = {
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 35)
};
// 使用 Lambda 表达式按年龄升序排序
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;
}
return 0;
}