需要头文件 algorithm
语法描述:sort(begin,end,cmp),cmp参数可以没有,如果没有默认非降序排序。
以int为例的基本数据类型的sort使用:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { int a[5]={1,3,4,2,5}; sort(a,a+5); for(int i=0;i<5;i++) cout<<a[i]<<' '; return 0; }
因为没有cmp参数,默认为非降序排序,结果为:
1 2 3 4 5
若设计为非升序排序,则cmp函数的编写:
bool cmp(int a,int b)
{
return a>b;
}
其实对于这么简单的任务(类型支持“<”、“>”等比较运算符),完全没必要自己写一个类出来。标准库里已经有现成的了,就在functional里,include进来就行了。functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。对于这个问题来说,greater和less就足够了,直接拿过来用:
升序:sort(begin,end,less());
降序:sort(begin,end,greater()).
复制代码
1
2
3
4
5
6
7
8
9
10
11
12int main ( ) { int a[20]={2,4,1,23,5,76,0,43,24,65},i; for(i=0;i<20;i++) cout<<a[i]<<endl; sort(a,a+20,greater<int>()); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }
- 引用数据类型string的使用
- 一个字符串间的个字符排序:
- 使用迭代器可以完成顺序排序
复制代码
1
2
3
4
5
6
7
8
9
10
11
12#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string str("hello world"); sort(str.begin(),str.end()); cout<<str; return 0; }
结果:空格dehllloorw
转载自:https://www.cnblogs.com/TX980502/p/8528840.html
最后
以上就是要减肥河马最近收集整理的关于c++ sort函数使用总结的全部内容,更多相关c++内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复