【发布时间】:2016-02-15 02:37:18
【问题描述】:
我的任务是读入一个包含游戏名称和分数的文件(文件看起来像)
5
John Doe 200
Chris Brown 340
Chris Brown 320
John Smith 300
John Doe 600
并按字母顺序(姓氏)打印出该人得分最高的姓名。所以输出看起来像:
Chris Brown 340
John Doe 600
John Smith 300
我想出了如何从最高到最低对分数进行排序和打印,但我不知道如何仅打印每个人的最高分数……任何帮助将不胜感激!
#include <iostream>
#include <fstream>
using namespace std;
struct playerscore
{
string first, last;
int score;
};
bool score(playerscore a, playerscore b);
void selectionsort(playerscore *A, int n);
int main()
{
string file;
int n;
cin >> file;
ifstream fin(file.c_str());
fin >> n;
// read in the names and the scores in the form of struct playerscore
playerscore *A = new playerscore[n];
for(int i = 0; i < n; i++)
fin >> A[i].first >> A[i].last >> A[i].score;
// sort the data
selectionsort(A, n);
// print in sorted order
for(int i = 0; i < n; i++)
cout << A[i].score << " ";
cout << endl;
return 0;
}
bool before(playerscore a, playerscore b)
{
return a.score > b.score;
}
void selectionsort(playerscore *A, int n)
{
for(int length = n; length > 1; length--)
{
//find imax, index of largest
int imax = 0, i;
for(i = 1; i < length; i++)
if(before(A[imax], A[i]))
imax = i;
// swap A[imax] and the last element
playerscore temp = A[imax];
A[imax] = A[length-1];
A[length-1] = temp;
}
}
【问题讨论】:
标签: c++ arrays sorting struct selection-sort