我正在尝试编写一个给出以下结构的程序:
struct aPlayer {
string name; // name of player
int wins; // number of wins player has
};
struct aCompetition {
string name; // name of the match
int numPlayers; // number of players in the club
aPlayer player[10]; // list of players in this club
};
从那里开始,我想写一个按字母顺序按名称对玩家进行排序的功能。函数声明如下:
void sortByName(aCompetition & c){}
注意:我想通过仅使用for循环,while循环和if语句来实现此目的。我能想到比较两个字符串的唯一方法是比较它们的ASCII值。我不知道该怎么做,所以任何输入都将非常感激。谢谢!
答案 0 :(得分:1)
排序由标准库提供,具有function checkStatus(response) {
let error = null;
if (!response.headers.get('Content-Type').includes('application/json')) {
error = new Error(response.statusText);
error.response = response;
throw error;
}
if (response.status >= 200 && response.status < 300) {
return response;
}
if (response.ok) {
return response;
}
const jsonData = response.json() ; // <- `jsonData` is a promise
error = new Error(/* How to extract error_message from json data? */);
error.response = response;
throw error;
}
的类型,或者如果给出比较器,则提供其他类型。您可以构建一个operator<
来进行词法比较。
string::operator<
如果您没有C ++ 11 lambdas,那么您就可以使用仿函数。
#include <algorithm>
void sortByName(aCompetition& c) {
sort(&c.player[0], &c.player[c.numPlayers],
[](const aPlayer& a, const aPlayer& b) {return a.name < b.name;});
}
答案 1 :(得分:1)
假设这是为家庭作业(如果不是这样,那么自己做这件事会比看到答案更能帮助你),我只想给你一些指导来帮助你。
比较ASCII值:
aPlayer player1, player2;
player1.name = "bill";
player2.name = "john";
if (player1.name[0] < player2.name[0])
{
// True, in this case, because b is less than j on the ascii table.
}
http://www.asciitable.com表示ascii值。我建议在玩家名称上使用tolower(),因为大写字母的值低于小写字母。
如果第一个数字相等,则转到第二个数字: (这样做的一种方法。)
aPlayer player1, player2;
player1.name = "alfred";
player2.name = "alvin";
// Find which name is shorter using .length() like player2.name.length()
// Loop through this next part for all aPlayers in aCompetition
for (int i = 0; i < shorterName.length(); i++)
{
// Compare ascii values as I showed above.
// If one is larger than the other, swap them.
}
答案 2 :(得分:0)
执行此操作的简单方法是将值存储为集合。这是一种在C ++中存储数据的相当标准的方法,并且具有按字母数字自动排序的优点。你必须绕过迭代器,但要有效地输出它们。
考虑这个执行:
std::set sortByNames(aCompetition & c, int numPlayers)
{
std::set<std::string> sortedNames;
for(int i = 0; i < numPlayers; i++)
{
std::string name;
//std::cout << i << ". ";
name = player[i];
sortedNames.insert(name);
}
return sortedNames;
}
从这里您可以使用它输出名称:
myNames = sortByNames(aCompetition, 10);
std::for_each(myNames.begin(), myNames.end(), &print);
您的头文件中还需要#include <set>
。