我的任務是與名,得分爲文件的遊戲讀取(文件看起來像)排序結構和數組
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;
}
}
因爲這個問題與「我的任務」開始,那麼我的假設是,這是家庭作業,他們都應該是學習如何排序和不準使用內置的排序功能。 – crashmstr
好點。但是,我從不傾向於做出假設。 – NTAuthority
那麼你應該也建議他們使用'std :: vector'而不是原始數組:) – crashmstr