本例中實現了金銀銅獎牌數降序排序,若兩個運動員金銀銅的獎牌數都相同,則按照運動員的姓名升序排序。ios
其中,關於結構體中的operator,這是其中一種寫法;看到有同事ysf用了另一種方法,看起來也比較清晰,下一個版本實現。函數
注意:這裏說的兩種寫法,都是在結構體中使用「bool operator <(const ScoreStruct &right) const」實現的,其實也能夠單獨拿出來,寫一個比較器函數,做爲sort()函數的第三個參數。再下下個版本實現。google
1 // Practice3_vector_sort_struct.cpp : 定義控制檯應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include <vector> 6 #include <algorithm> 7 #include <iostream> 8 #include <ctime> 9 #include <stdio.h> 10 #include <string> 11 12 using namespace std; 13 14 struct ScoreStruct 15 { 16 string name; 17 unsigned int gold; 18 unsigned int silver; 19 unsigned int bronze; 20 bool operator <(const ScoreStruct &right) const 21 { 22 int temp = name.compare(right.name); 23 if(gold != right.gold)//首先按照金銀銅牌數降序,若是都相等,則按照姓名升序 24 { 25 return gold > right.gold; 26 } 27 else 28 { 29 if(silver != right.silver) 30 { 31 return silver > right.silver; 32 } 33 else 34 { 35 if(bronze != right.bronze) 36 { 37 return bronze > right.bronze; 38 } 39 else if(temp < 0) 40 { 41 return 1; 42 } 43 } 44 } 45 return 0;//不管如何,要保證最後要有一個return的 46 } 47 }; 48 49 string strs[4] = { "tencent", "google","alibaba", "facebook"}; 50 51 void initVector(vector<ScoreStruct> &vec, unsigned int size) 52 { 53 srand(unsigned(time(NULL))); 54 for(unsigned int i =0; i < size; i++) 55 { 56 //char buff[32] = {0}; 57 int goldCount = rand()%100; 58 int silverCount = rand()%100; 59 int bronzeCount = rand()%100; 60 //sprintf(buff, "%d", chineseScore); 61 ScoreStruct ss = {strs[i], goldCount, silverCount, bronzeCount}; 62 /* 63 ScoreStruct ss = {"0", 0}; 64 strcpy(ss.name, buff); 65 ss.score = randNum; 66 */ 67 vec.push_back(ss); 68 } 69 } 70 71 void printVector(vector<ScoreStruct> vec) 72 { 73 vector<ScoreStruct>::iterator it = vec.begin(); 74 for(; it != vec.end();++it) 75 { 76 cout << it->name << "," << it->gold << "," << it->silver << "," << it->bronze << " "; 77 } 78 cout<<endl; 79 } 80 81 int _tmain(int argc, _TCHAR* argv[]) 82 { 83 vector<ScoreStruct> vect; 84 initVector(vect, 4); 85 cout<<"before sort"<<endl; 86 printVector(vect); 87 sort(vect.begin(), vect.end()); 88 cout<<"after sort"<<endl; 89 printVector(vect); 90 return 0; 91 }
運行結果示例1(這個結果很好,剛好隨機到有兩名player金牌數相同,則按照銀牌排序):spa
before sort
tencent,93,65,21 google,93,41,86 alibaba,77,88,35 facebook,81,87,25
after sort
tencent,93,65,21
google,93,41,86
facebook,81,87,25
alibaba,77,88,35code
運行結果示例2(這個例子故意把金銀銅數量設置爲相同,結果代表很好滴實現了需求):blog
before sort
tencent,6,6,6 google,6,6,6 alibaba,6,6,6 facebook,6,6,6
after sort
alibaba,6,6,6 facebook,6,6,6 google,6,6,6 tencent,6,6,6
排序