sort c++使用
时间: 2023-12-04 19:41:38 浏览: 25
以下是使用sort函数进行排序的C++代码示例:
引用:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a, int b);
int main() {
int a[] = {45, 12, 34, 77, 90, 11, 2, 4, 5, 55};
sort(a, a + 10, cmp);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
bool cmp(int a, int b) {
return a > b;
}
```
引用:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[] = {45, 12, 34, 77, 90, 11, 2, 4, 5, 55};
sort(a, a + 10);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
return 0;
}
```
sort函数是C++ STL中的一个排序函数,可以对数组、向量等容器进行排序。sort函数的基本语法如下:
```c++
sort(first, last, cmp);
```
其中,first和last分别是容器中要排序的元素的起始位置和结束位置,cmp是一个可选的比较函数,用于指定排序规则。如果不指定cmp,则默认按照从小到大的顺序排序。