sort()在c++
时间: 2023-11-20 19:55:25 浏览: 27
sort()是C++ STL中的一个函数,用于对数组或容器中的元素进行排序。sort()函数有两种调用方式:默认方式和自定义方式。默认方式会按照元素的大小进行排序,而自定义方式则可以根据用户自定义的比较函数进行排序。
以下是sort()函数的两种调用方式的示例代码:
1.默认方式
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:1 2 5 5 6 9
2.自定义方式
```c++
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, cmp);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:9 6 5 5 2 1
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)