c++ sort自定义排序
时间: 2023-08-20 07:06:48 浏览: 52
在C++中,可以使用`std::sort`函数来对容器进行排序。如果想要进行自定义排序,可以通过传递一个自定义的比较函数或者一个lambda表达式来实现。
下面是一个示例代码,展示了如何使用自定义排序函数对一个vector进行排序:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// 自定义排序函数
bool customSort(int a, int b) {
// 按照元素的绝对值进行排序
return abs(a) < abs(b);
}
int main() {
std::vector<int> nums = {5, -2, 3, -1, 4};
// 使用自定义排序函数对nums进行排序
std::sort(nums.begin(), nums.end(), customSort);
// 打印排序后的结果
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:-1, 3, -2, 4, 5,按照元素的绝对值进行排序。
另外,你也可以使用lambda表达式来实现自定义排序。下面是一个使用lambda表达式进行自定义排序的示例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, -2, 3, -1, 4};
// 使用lambda表达式进行自定义排序
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return abs(a) < abs(b);
});
// 打印排序后的结果
for (int num : nums) {
std: