c++sort函數的使用總結

sort類函數:ios

函數名 功能描述
sort 對給定區間全部元素進行排序
stable_sort 對給定區間全部元素進行穩定排序
partial_sort 對給定區間全部元素部分排序
partial_sort_copy 對給定區間複製並排序
nth_element 找出給定區間的某個位置對應的元素
is_sorted 判斷一個區間是否已經排好序
partition 使得符合某個條件的元素放在前面
stable_partition 相對穩定的使得符合某個條件的元素放在前面

須要頭文件<algorithm>less

語法描述:sort(begin,end,cmp),cmp參數能夠沒有,若是沒有默認非降序排序。函數

以int爲例的基本數據類型的sort使用this

#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參數,默認爲非降序排序,結果爲:spa

1 2 3 4 5設計

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

bool cmp(int a,int b)對象

{blog

  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;
 } 
相關文章
相關標籤/搜索