2017-04-07 257 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()); 
}