这个例子很典型,程序中写的是按照语数外的分数降序排序,这里可以看成赛场上的金银铜牌的数据降序,完全是等同的。
若一个人的金牌个数相同,则按银牌个数排序,以此类推。
下一版将首先按照选手的姓名字母排序。
// Practice3_vector_sort_struct.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <stdio.h>
#include <string>
using namespace std;
struct ScoreStruct
{
string name;
unsigned int chinese;
unsigned int math;
unsigned int english;
bool operator <(const ScoreStruct &right) const
{
if(chinese != right.chinese)
{
return chinese > right.chinese;//大于,即降序排序;若为小于,则升序排序
}
else
{
if(math != right.math)
{
return math > right.math;
}
else
{
return english > right.english;
}
}
}
};
void initVector(vector<ScoreStruct> &vec, unsigned int size)
{
srand(unsigned(time(NULL)));
for(unsigned int i =0; i < size; i++)
{
char buff[32] = {0};
int chineseScore = rand()%100;
int mathScore = rand()%100;
int englishScore = rand()%100;
sprintf(buff, "%d", chineseScore);//默认以语文成绩作为考生的姓名
ScoreStruct ss = {buff, chineseScore, mathScore, englishScore};
/*
ScoreStruct ss = {"0", 0};
strcpy(ss.name, buff);
ss.score = randNum;
*/
vec.push_back(ss);
}
}
void printVector(vector<ScoreStruct> vec)
{
vector<ScoreStruct>::iterator it = vec.begin();
for(; it != vec.end();++it)
{
cout << it->name << "," << it->chinese << "," << it->math << "," << it->english << " ";
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<ScoreStruct> vect;
initVector(vect, 4);
cout<<"before sort"<<endl;
printVector(vect);
sort(vect.begin(), vect.end());
cout<<"after sort"<<endl;
printVector(vect);
return 0;
}