2017-04-07 29 views
1

我想写给出以下结构的程序:排序字符串数组按字母C++

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){} 

注:我想通过只使用循环来做到这一点,while循环,如果声明(S)。我能想到比较两个字符串的唯一方法是比较它们的ASCII值。我不知道如何做到这一点,所以任何输入将不胜感激。谢谢!

+0

的std :: string支持小于和大于比较。我会使用std :: sort,但是如果你只限于你可以使用的简单的冒泡排序,那么很好,你可以很容易地找到该算法。 –

+0

aCompetition应该是一个结构吗?考虑到它拥有一个数组? – Krythic

+0

似乎完全正常于我。比赛包含球员。 –

回答

0

假设这是对家庭作业(如果它不是由自己做,这将帮助你很多不仅仅是看到了答案,)我只是想给你几个指针来帮助你。

比较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. 
} 
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>

0

排序由标准库提供,类型为operator<或其他类型(如果使用比较器)。你可以建立一个关闭string::operator<执行词法比较。

#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;}); 
} 

如果你没有C++ 11 lambda,那么你会使用一个仿函数。

struct compareAPlayerByName { 
    boolean operator()(const aPlayer& a, const aPlayer& b) { 
     return a.name < b.name; 
    } 
}; 
void sortByName(aCompetition& c) { 
    sort(&c.player[0], &c.player[c.numPlayers], compareAPlayerByName()); 
}