c++ sort函数由小到大排序
时间: 2023-11-24 19:50:41 浏览: 34
以下是使用C++的sort函数进行由小到大排序的例子:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a < b;
}
int main() {
int arr[] = {5, 2, 8, 4, 7};
int len = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + len, cmp);
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:2 4 5 7 8
其中,sort函数的第一个参数为待排序数组的起始地址,第二个参数为待排序数组的结束地址的下一个地址,第三个参数为排序准则,如果不写则默认从小到大排序。在本例中,我们自定义了一个cmp函数,用于实现从小到大排序。
相关问题
sort函数如何从大到小排序
sort函数默认是从小到大排序,如果要从大到小排序,可以使用自定义比较函数。可以使用Lambda表达式或者函数指针来实现。以下是使用Lambda表达式的示例代码:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8};
sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b;
});
for (auto num : nums) {
cout << num << " ";
}
return 0;
}
```
输出为:9 8 6 5 5 5 4 3 3 2 1 1
Lambda表达式`[](int a, int b) { return a > b; }`表示如果a大于b,则返回true,否则返回false,即从大到小排序。
c++sort函数自定义排序
在C++中,可以使用`std::sort`函数来对数据进行排序。如果您想要自定义排序规则,可以使用函数指针或者函数对象作为`std::sort`的第三个参数。
以下是一个示例,演示如何使用自定义函数来对一个整数数组进行排序:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// 自定义排序函数
bool customSort(int a, int b) {
// 根据自己的排序规则来确定a和b的顺序
// 这里使用的是按照数字的绝对值大小进行排序
return abs(a) < abs(b);
}
int main() {
std::vector<int> numbers = {5, -3, 2, -10, 8};
// 使用自定义排序函数对数组进行排序
std::sort(numbers.begin(), numbers.end(), customSort);
// 输出排序后的结果
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
```
在上面的示例中,自定义排序函数`customSort`根据数字的绝对值大小来确定顺序。通过将`customSort`作为第三个参数传递给`std::sort`函数,可以使得数组按照自定义规则进行排序。
请注意,自定义排序函数需要满足严格弱排序准则,即对于任意的元素a、b和c,如果`customSort(a, b)`返回true,则`customSort(b, a)`必须返回false,并且如果`customSort(a, b)`和`customSort(b, c)`都返回true,那么`customSort(a, c)`也必须返回true。
希望这个示例能够对您有所帮助!如果您有其他问题,请随时提问。