上一個程序中說,「有同事ysf用了另一種方法,看起來也比較清晰,下一個版本實現」。ios
發如今實現的過程當中,又有一個比較節省代碼行(應該也會提高一點效率)的寫法。google
上一個程序中還說,在下下個版本實現使用比較器做爲sort()的第三個參數實現,則,下一個版本實現。spa
不一樣的地方是operator的實現(對,就是在if語句上,我直接用的!=,這樣能夠少寫一個else):code
bool operator <(const ScoreStruct &right) const { int temp = name.compare(right.name); if(gold != right.gold)//首先按照金銀銅牌數降序,若是都相等,則按照姓名升序 { return gold > right.gold; } ,,,return 0;//不管如何,要保證最後要有一個return的 }
同事ysf的實現方式是(這樣會多寫一個else):blog
bool compbyGSB(const countrymsg& c1 , const countrymsg& c2) { if(c1.gold > c2.gold) { return true ; } else if(c1.gold < c2.gold) { return false ; } ,,,return false ; }
完整程序:string
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 28 if(silver != right.silver) 29 { 30 return silver > right.silver; 31 } 32 33 if(bronze != right.bronze) 34 { 35 return bronze > right.bronze; 36 } 37 38 if(temp <0) 39 { 40 return 1; 41 } 42 return 0;//不管如何,要保證最後要有一個return的 43 } 44 }; 45 46 string strs[4] = { "tencent", "google","alibaba", "facebook"}; 47 48 void initVector(vector<ScoreStruct> &vec, unsigned int size) 49 { 50 srand(unsigned(time(NULL))); 51 for(unsigned int i =0; i < size; i++) 52 { 53 //char buff[32] = {0}; 54 int goldCount = rand()%100; 55 int silverCount = rand()%100; 56 int bronzeCount = rand()%100; 57 //sprintf(buff, "%d", chineseScore); 58 ScoreStruct ss = {strs[i], goldCount, silverCount, bronzeCount}; 59 /* 60 ScoreStruct ss = {"0", 0}; 61 strcpy(ss.name, buff); 62 ss.score = randNum; 63 */ 64 vec.push_back(ss); 65 } 66 } 67 68 void printVector(vector<ScoreStruct> vec) 69 { 70 vector<ScoreStruct>::iterator it = vec.begin(); 71 for(; it != vec.end();++it) 72 { 73 cout << it->name << "," << it->gold << "," << it->silver << "," << it->bronze << " "; 74 } 75 cout<<endl; 76 } 77 78 int _tmain(int argc, _TCHAR* argv[]) 79 { 80 vector<ScoreStruct> vect; 81 initVector(vect, 4); 82 cout<<"before sort"<<endl; 83 printVector(vect); 84 sort(vect.begin(), vect.end()); 85 cout<<"after sort"<<endl; 86 printVector(vect); 87 return 0; 88 }