按照結構體數組的某一項排序,那麼一個結構體包含的其餘元素仍保持不變。也就是說只能選擇其中一項做爲指標進行排序,相應的其餘值對應不變化。ios
以下圖,排序前數組爲:1,3;8,4;5,2;數組
排序後仍然是它們的組合,只是順序變了而已。spa
結果以下:code
代碼:blog
1 #include<algorithm>
2 #include<iostream>
3 using namespace std; 4
5 const int M = 3; 6
7 struct two { 8 double w; 9 double v; 10 }ss[M]; 11 bool cmp(two a,two b) 12 { 13 return a.v > b.v; //按照從大到小排序
14 } 15
16 int main() 17 { 18 int s, e; 19 cout << "輸入結構體數組的數值,以空格分開: " << endl; 20 for (int i = 0; i < 3; ++i) 21 { 22 cin >> s >> e; 23 ss[i].w = s; 24 ss[i].v = e; 25 //cout << ss[i].w << " " << ss[i].v << endl;
26 } 27 sort(ss, ss + 2, cmp); 28
29 cout << "排序後以下:" << endl; 30 for (int i = 0; i < 3; ++i) 31 { 32 cout << ss[i].w << " " << ss[i].v << endl; 33 } 34
35 cin.ignore(); 36 cin.ignore(); 37 cin.ignore(); 38
39
40 return 0; 41 }