C++ STL排序

1. int數組區間從小到大排序:比如說把第2個元素到第5個元素從小到大排好序。

sort(a + 1, a + 5);

注意這裏排序的區間是[1, 5),左閉右開,不包括下標爲5(也就是第6個)元素。

整個數組從小到大排序,從第一個元素到第n個元素:

sort(a, a + n);

換句話說,就是左邊減一,右邊不變。

 

2.整個int數組從大到小排序

sort(a, a + n, greater<int>()); 

其中int是數組元素的類型,也可以是double,char,或者其它自定義類型。

 

3.整個int數組按照自定義規則排序

假設自定義規則爲按照個位數從小到大排序

struct rule
{
    bool operator()(const int &a, const int &b) const
    {
        return a % 10 < b % 10;
    }
};

sort(a, a + n, rule());

 

4.結構體數組自定義規則排序

現有學生的姓名、學號、成績,規定排序規則爲按照成績從高到低排序,如果成績相同,則按名字的字典序排序。

#include <bits/stdc++.h>
using namespace std;

struct student
{
    char name[20];
    int id;
    double gpa;
};

student s[] =  { 
{"Jack",112,3.4},{"Mary",102,3.8},{"Mary",117,3.9},
{"Ala",333,3.4},{"Zero",101,4.0}
};


struct rule
{
    bool operator()(const student &a, const student &b) const
    {
        if(a.gpa > b.gpa)
            return true;
        else if(a.gpa == b.gpa && strcmp(a.name, b.name) < 0)
            return true;
        else
            return false;
        
    }
};
int main()
{
    
    int n = sizeof(s) / sizeof(student);
    sort(s, s + n, rule());
    for(int i = 0; i < n; i++)
        cout << s[i].gpa << " " << s[i].name  << " " << s[i].id << endl;
    return 0;
}

 

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