標籤:[] 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++排序