天天看點

C++中的sort

原型:

void sort(_RandomAccessIterator __first, _RandomAccessIterator __last,

_Compare __comp)

  • __first:排序區間的起始位址
  • __last:排序區間的末尾位址
  • __comp:排序方法

以上排序區間依然是左閉右開

兩個參數時,預設升序

vector<int> v = {3,1,4,6,0,9};
sort(v.begin(), v.end());//升序
int a[6] =  {3,1,4,6,0,9};
sort(a, a+6);//升序      

自定義排序方法

1、升序

bool cmp(const int a, const int b){
    return a < b;
}
int main(){
    vector<int> v = {3,1,4,6,0,9};
    sort(v.begin(), v.end(), cmp);
    return 0;
}      

2、降序

bool cmp(const int a, const int b){
    return a > b;
}
int main(){
    vector<int> v = {3,1,4,6,0,9};
    sort(v.begin(), v.end(), cmp);
    return 0;
}      

若排序的資料類型支援“<”、“>”等比較運算符,則可以使用STL中提供的函數

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

上述的begin,end表示位址,不是索引

<int> v = {3,1,4,6,0,9};
    sort(v.begin(), v.end(), less<int>());//升序
    sort(v.begin(), v.end(), greater<int>());//降序      

結構體排序

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct Person{
    float height;
    float weight;
    Person(float h, float w){
        height = h;
        weight = w;
    }
};

//身高不同按照身高降序,身高相同按照體重降序
bool cmp(Person p1, Person p2){
    if(p1.height != p2.height){
        return p1.height > p2.height;
    }else{
        return p1.weight > p2.weight;
    }
}

int main(){
    vector<Person> persons = {Person(160, 100), Person(170, 130), Person(170, 120), Person(180, 100)};
    sort(persons.begin(), persons.end(), cmp);
    for(auto p : persons){
        cout<<p.height<<" "<<p.weight<<endl;
    }
    return 0;
}