1. 程式人生 > >c++中sort基礎用法

c++中sort基礎用法

  • 用法一:陣列排序

           對一個數組進行升序排序

#include <algorithm>
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int a[100]={8,9,10,6,5,4};
    sort(a,a+6);
    for(int i=0;i<6;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

sort包含在#include<algorithm>中,sort(陣列頭,陣列尾),sort(a,a+6)可以看作sort(a+0,a+6)表示對陣列a的第0個元素到第5個元素進行排序。預設排序方式為升序排序。

如果想進行降序排序則需要引入自定義排序規則compare

#include <algorithm>
#include <iostream>
#include <cstdio>

using namespace std;
bool compare(int a,int b){
    return a>b;
}
int main()
{
    int a[100]={8,9,10,6,5,4};
    sort(a,a+6,compare);
    for(int i=0;i<6;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

  • 用法2:結構體排序

有時我們會遇到這樣的問題,按學生成績進行降序排序,如果成績相同按學號升序排序,怎麼用sort解決這個問題呢?

​
struct student{
    int num;            //學號
    int score;          //成績
};

bool cmp(student a,student b){//按成績降序,再按學號升序
    if(a.score>b.score)return a.num<b.num;
    return a.score>b.score;
}

struct student stu[10];
//輸入學生資料
sort(a,a+10,cmp);

​
  • 用法3:動態陣列vector內的排序
vector<int>s;
sort(s.begin(),s.end());

注意事項:sort內集成了多種演算法,時間複雜度會比n*n小但並不是nlogn