我遇到了一些学校工作的问题,我需要创建两个阵列,一个用于名称,一个用于分数,允许用户输入两个阵列(即输入球员名称:;输入球员得分:) 。然后我需要以降序打印数组,然后按字母顺序升序。作为提示我们被告知:使用字符串排序功能将两个数组合并为一个然后排序。
但是我无法弄清楚如何将这两个值相互联系起来,这样如果我以87的分数输入Nathan,则两个值不能分开。
这是我到目前为止所做的事情(有些事情我试图开始工作但不能):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string names[10];
int scores[10];
string combine[20];
int count = 0;
while (count < 10){
cout << "Please enter a player's name: ";
cin >> names[count];
cout << "Now enter that player's score: ";
cin >> scores[count];
count++;
}
/*sort(begin(names), end(names));
sort(begin(scores), end(scores));*/
for (int i = 0; i < 10; i++){
cout << names[i] << ": " << scores[i] << "\n";
}
system("pause");
}
答案 0 :(得分:0)
您想从一开始就“链接”它们:
sort(begin(students), end(students));
这样,排序很简单:
int indices[10];
std::iota(begin(indices), end(indices), 0);
否则,你必须制作一系列索引:
std::sort(begin(indices), end(indices), [&](int a, int b){
return scores[a] > scores[b] ||
scores[a] == scores[b] && names[a] < names[b];
});
然后排序:
for (int idx : indices) {
std::cout << names[idx] << " with score " << scores[idx] << '\n';
}
然后根据指数打印:
{{1}}
答案 1 :(得分:0)
只要将两个数组合并为一个,就可以这样做:
// create a struct that of type "result"
// that combines both name and score
struct result
{
string name;
int score;
};
int main()
{
string names[10];
int scores[10];
// array of your struct - same number of elements (10 not 20)
result combine[10];
int count = 0;
while (count < 10){
cout << "Please enter a player's name: ";
cin >> names[count];
cout << "Now enter that player's score: ";
cin >> scores[count];
count++;
}
/*sort(begin(names), end(names));
sort(begin(scores), end(scores));*/
for (int i = 0; i < 10; i++){
cout << names[i] << ": " << scores[i] << "\n";
}
// combine into one array
for(int i = 0; i < 10; ++i)
{
combine[i].name = names[i];
combine[i].score = scores[i];
}
// Now sort the combined array
system("pause");
}