附录B sort函数
我们可以利用C++中的排序函数sort,对古董的重量进行从小到大排序。要使用此函数,只需引入头文件:
#include <algorithm>
语法描述为:
sort(begin, end)// 参数begin, end表示一个范围,分别为待排序数组的首地址和尾地址。
例如:
//mysort1
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={7,4,5,23,2,73,41,52,28,60},i;
for(i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a,a+10);
for(i=0;i<10;i++)
cout<<a[i]<<" ";
return 0;
}
输出结果为:
7 4 5 23 2 73 41 52 28 60
2 4 5 7 23 28 41 52 60 73
sort(a,a+10)将把数
这篇博客介绍了C++中sort函数的使用,包括如何进行升序和降序排序。通过引入头文件,可以使用sort函数对数组进行排序。对于降序排序,可以通过自定义compare函数或者利用functional标准库中的greater和less比较函数对象实现。
订阅专栏 解锁全文
4017

被折叠的 条评论
为什么被折叠?



