C++排序

來源:互聯網
上載者:User

標籤:[]   main   image   問題   return   out   定義   檔案   opera   

C++排序一、心得

有多個資料的,無腦排個序,會使問題好想很多

sort(數組起始指標,數組尾指標,定序);

 

 

二、排序詳細

1、所需標頭檔:

<algorithm>

2、排序方法:

sort(數組起始指標,數組尾指標,定序);

數組起始指標,數組尾指標是左閉右開

定序可以省略,也可以用系統的,也可以自己寫

3、例子:

int a[]={9,2,4,5,10,7,30};

sort(a,a+7);

這是預設的對數組從小到大排列

 

三、代碼及結果

 

 1 #include <iostream> 2 #include <algorithm> 3 #include <string> 4 using namespace std; 5  6 //結構體排序一 7 //按姓名從小到大排序,姓名一樣,按年齡從小到大排序  8 struct student{ 9     string name;//姓名 10     int age;//年齡 11 }; 12 int comp(const student &s1,const student &s2){//自己定義的定序 13     if(s1.name==s2.name){14         return s1.age<s2.age;15     }16     else{17         return s1.name<s2.name;18     }19 } 20 //結構體排序二21 //按姓名從小到大排序,姓名一樣,按年齡從小到大排序 22 struct student2{23     string name;//姓名 24     int age;//年齡 25     bool operator < (const student2 & s2) const {//符號重載 26         if(name==s2.name){27             return age<s2.age;28         }29         else{30             return name<s2.name;31         }32     }33 }; 34 int main(){35     //普通數組排序  36     int a[]={9,2,4,5,10,7,30};37     sort(a,a+7);//省略掉定序的形式,預設從小到大 38     sort(a,a+7,less<int>());//用系統的定序,從小到大 39     sort(a,a+7,greater<int>());//用系統的定序,從大到小 40     for(int i=0;i<7;i++){41         cout<<a[i]<<" ";42     }43     cout<<endl; 44     //結構體數組排序一 45     student s[100];46     s[0].name="zhangsan";s[0].age=18;47     s[1].name="zhangsan";s[1].age=19;48     s[2].name="lisi";s[2].age=20;49     sort(s,s+3,comp);//左閉右開,所以是對s[0]到s[2]排序 50     for(int i=0;i<3;i++){51         cout<<s[i].name<<" "<<s[i].age<<endl;52     }53     //結構體數組排序二:符合重載54     student2 s2[100]; 55     s2[0].name="zhangsan";s2[0].age=18;56     s2[1].name="zhangsan";s2[1].age=19;57     s2[2].name="lisi";s2[2].age=20;58     sort(s2,s2+3);//左閉右開,所以是對s[0]到s[2]排序 59     for(int i=0;i<3;i++){60         cout<<s2[i].name<<" "<<s2[i].age<<endl;61     }62     63     64     return 0;65 } 

 

C++排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.