c++函数自定义排序
时间: 2025-05-07 19:19:59 浏览: 31
### C++ 中实现自定义排序
在 C++ 中,`std::sort` 函数可以接受第三个参数作为比较函数,用于指定自定义的排序逻辑。以下是几种常见的方法来实现自定义排序。
#### 使用独立的比较函数
可以通过编写一个单独的布尔返回类型的函数来进行自定义排序。此函数接收两个待比较的对象并决定它们之间的顺序:
```cpp
#include <algorithm>
#include <vector>
#include <cmath>
bool compareAbsolute(int a, int b) {
return std::abs(a) < std::abs(b);
}
int main() {
std::vector<int> nums = {-4, 2, -8, 5, -1, 7};
std::sort(nums.begin(), nums.end(), compareAbsolute); // 现在 nums = {-1, 2, -4, 5, 7, -8}
return 0;
}
```
这种方法简单明了,适用于简单的排序条件[^1]。
#### 利用 Lambda 表达式
对于更简洁的方式,在现代 C++ (C++11 及以上版本),推荐使用 lambda 表达式代替命名函数。这使得代码更加紧凑且易于理解:
```cpp
#include <algorithm>
#include <vector>
#include <cmath>
int main() {
std::vector<int> nums = {-4, 2, -8, 5, -1, 7};
auto absCompare = [](const int& lhs, const int& rhs){
return std::abs(lhs) < std::abs(rhs);
};
std::sort(nums.begin(), nums.end(), absCompare);
return 0;
}
```
Lambda 的优势在于其局部性和内联特性,减少了全局作用域污染的可能性[^2]。
#### 结构体内的运算符重载
当需要对复杂数据结构进行排序时,可以在该类或结构体内定义 `operator<` 来提供自然序关系。这样可以直接调用 `std::sort()` 而无需额外传递比较器:
```cpp
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
bool operator<(const Person& other)const{
if(age != other.age)
return age < other.age;
else
return name < other.name;
}
};
void printPeople(const std::vector<Person>& people){
for(auto&& person : people){
std::cout << "Name: " << person.name << ", Age:" << person.age << '\n';
}
}
int main(){
std::vector<Person> persons{{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}};
std::sort(persons.begin(), persons.end());
printPeople(persons);
return 0;
}
```
在这个例子中,通过重写 `<` 运算符实现了基于年龄升序排列;如果两个人具有相同的年龄,则按名字字母表顺序进一步区分。
阅读全文
相关推荐


















