sort()函數使用詳解


使用時需要導入頭文件<algorithm>

#include<algorithm>

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

一.以int為例的基本數據類型的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;
 }

因為沒有cmp參數,默認為非降序排序,結果為:

1 2 3 4 5

若設計為非升序排序,則cmp函數的編寫:

bool cmp(int a,int b)

{

  return a>b;

}

其實對於這么簡單的任務(類型支持“<”、“>”等比較運算符),完全沒必要自己寫一個類出來。標准庫里已經有現成的了,就在functional里,include進來就行了。functional提供了一堆基於模板的比較函數對象。它們是(看名字就知道意思了):equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>。對於這個問題來說,greater和less就足夠了,直接拿過來用:

升序:sort(begin,end,less<data-type>());

降序:sort(begin,end,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的使用

一個字符串間的個字符排序:

使用迭代器可以完成順序排序

#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;
 }
結果:wroolllhde空格

字符串間的比較排序

#include<iostream>
#include<cstring >
#include<algorithm>
using namespace std;
int main()
{
    string a[4];
    for(int i=0;i<4;i++)
        getline(cin,a[i]);
    sort(a,a+4);
    for(int i=0;i<4;i++)
        cout<<a[i]<<endl;
    return 0;
}

三.以結構體為例的二級排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct link
{
    int a,b;
};
bool cmp(link x,link y)
{
    if(x.a==y.a)
        return x.b>y.b;
    return x.a>y.a;
}
int main()
{
    link x[4];
    for(int i=0;i<4;i++)
        cin>>x[i].a>>x[i].b;
    sort(x,x+4,cmp);
    for(int i=0;i<4;i++)
        cout<<x[i].a<<' '<<x[i].b<<endl;
    return 0;
 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM