sort()排序函數

原文鏈接:https://www.cnblogs.com/TX980502/p/8528840.html

需要頭文件<algorithm>

語法描述:sort(begin,end,cmp),cmp參數可以沒有,如果沒有默認升序排序。

int數據類型的sort排序

sort函數使用實例

#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;
 }

如果要使用降序排序則在第三個參數添加greater<data-type>()

例如:

int  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類型的sort排序

#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

逆序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    string str("hello world");
    sort(str.rbegin(),str.rend());
    cout<<str;
    return 0;
 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章