0

我正在尝试将选择排序实现为类中的成员函数,以对通过用户输入获得总玩家数量的类的对象进行排序,同时用户也获得玩家的姓名和分数。

我将按玩家对象的分数属性对玩家对象进行排序,分数是类成员,由用户输入获得。

我的问题是,我陷入了无法为对象数组调用类的成员函数排序的主要内容中。

class Player{
private:
string name;
int score;

public:
void setStatistics(string, int) // simple setter, not writing the whole function
void sortPrint(int, Player []);
int getScore(){ return score; }
void print(){ cout << name << " " << score << endl; }
};

void Player::sortPrint(int n, Player arr[]){
int i, j, minIndex;
Player tmp;

for (i = 0; i < n - 1; i++) {
    int maxIndex = i;
    for (j = i + 1; j < n; j++) 
    {
          if (arr[j].getScore() > arr[minIndex].getScore())
          {
                minIndex = j;
          }
    }

    if (minIndex != i) {
          tmp = arr[i];
          arr[i] = arr[minIndex];
          arr[minIndex] = tmp;
    }

for(int i=0; i<n; i++){
arr[i].print(); // not sure with this too
}

}

};

int main(){
int n,score;
string name;

cout << "How many players ?" << endl;
cin >> n;

Player **players;
players = new Player*[n]; 

for(int i=0;i<n;i++) {

cout << "Player's name :" << endl;
cin >> name;
cout << "Player's total score:" << endl;
cin >> score;
players[i] = new Player;
players[i]->setStatistics(name,score); 

}

for(int i=0; i<n;i++){
players->sortPrint(n, players); // error here, dont know how to do this part
}

// returning the memory here, didn't write this part too.

}
4

3 回答 3

0

你的问题是,这players是一个指向数组的指针Player,而数组没有容器的成员函数。asPlayer::sortPrint不依赖于对象本身,将其声明为static并调用它 likePlayer::sortPrint(n, players);

于 2013-10-22T07:49:00.977 回答
0

尝试替换void Player::sortPrint(int n, Player arr[])void Player::sortPrint(int n, Player*)调用函数,如players->sortPrint(n, *players)

于 2013-10-22T07:47:15.423 回答
0

除非你有很好的理由不这样做,否则你应该使用std::sort而不是你自己的排序算法。您应该使用比较功能来比较每个玩家的得分。

以下应该在 C++03 中工作:

bool comparePlayerScores(const Player* a, const player* b)
{
    return (a->getScore() < b->getScore());
}


// Returns the players sorted by score, in a new std::vector
std::vector<Player*> getSortedPlayers(Player **players, int num_players)
{
    std::vector<Player*> players_copy(players, players + num_players);
    std::sort(players_copy.begin(), players_copy.end(), comparePlayerScores);
    return players_copy;
}

void printSorted(Player **players, int num_players)
{
    std::vector<Player*> sorted_players = getSortedPlayers(players, num_players);
    // Could use iterators here, omitting for brevity
    for (int i = 0; i < num_players; i++) {
        sorted_players[i]->print();
    }
}

(或者,您可以operator<Player比较分数的类上定义 a ,这样您就可以将玩家存储在 astd::setstd::map中。)

于 2013-10-22T07:54:50.220 回答