上一个程序中说,“有同事ysf用了另外一种方法,看起来也比较清晰,下一个版本实现”。
发现在实现的过程中,又有一个比较节省代码行(应该也会提升一点效率)的写法。
上一个程序中还说,在下下个版本实现使用比较器作为sort()的第三个参数实现,则,下一个版本实现。
不同的地方是operator的实现(对,就是在if语句上,我直接用的!=,这样可以少写一个else):
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):
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 ; }
完整程序:
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 }