按属性排序的C ++动态对象数组

时间:2013-10-22 07:32:53

标签: c++ arrays class sorting

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

我会根据用户输入得到的分数属性(即类成员)对玩家对象进行排序。

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

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.

}

3 个答案:

答案 0 :(得分:0)

尝试将void Player::sortPrint(int n, Player arr[])替换为void Player::sortPrint(int n, Player*)并调用players->sortPrint(n, *players)

之类的函数

答案 1 :(得分:0)

您的问题是,players是指向Player数组的指针,并且数组没有容器的成员函数。由于Player::sortPrint不依赖于对象本身,因此将其声明为static并将其称为Player::sortPrint(n, players);

答案 2 :(得分: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来比较分数,这样可以让您将玩家存储在std::setstd::map中。)