本例中实现了金银铜奖牌数降序排序,若两个运动员金银铜的奖牌数都相同,则按照运动员的姓名升序排序。
其中,关于结构体中的operator,这是其中一种写法;看到有同事ysf用了另外一种方法,看起来也比较清晰,下一个版本实现。
注意:这里说的两种写法,都是在结构体中使用“bool operator <(const ScoreStruct &right) const”实现的,其实也可以单独拿出来,写一个比较器函数,作为sort()函数的第三个参数。再下下个版本实现。
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金牌数相同,则按照银牌排序):
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,35
运行结果示例2(这个例子故意把金银铜数量设置为相同,结果表明很好滴实现了需求):
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