版权声明:from:Jihome https://blog.csdn.net/jihome/article/details/88918637
排序函数是很好用的,C++中是自带了排序函数的,那就是sort函数的,下面就是对sort函数的使用总结,为了在编程更有效率,了解一些内置函数是很有用的。
参考博客:T.X.
源代码如下(有具体注释):
/**sort函数的使用*/
#include <iostream>
#include <algorithm>//sort函数要包含的头文件
#include <cstring>
using namespace std;
int main(){
int a[5]={2,1,3,4,5};
string s="hello world";
int i;
sort(a,a+5,less<int>());//对Int型的sort greater(降序) less(升序)
for(i=0;i<5;i++){
cout<<a[i]<<" ";
}
sort(s.begin(),s.end());//字符串的排序(正序)
cout<<endl<<s<<endl;
sort(s.rbegin(),s.rend());//逆序(反向迭代器实现)
cout<<s<<endl;
string str[3]; //字符串之间的比较
for(i=0;i<3;i++){
getline(cin,str[i]);
}
sort(str,str+3);
for(i=0;i<3;i++){
cout<<str[i]<<endl;
}
return 0;
}