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

C++ Dynamic Array of Objects Sorting by Property

本文关键字:对象 动态 数组 排序 属性 C++      更新时间:2023-10-16

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

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

我的问题是,我卡在 main 中,我无法为对象数组调用类的成员函数排序。

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.
}
尝试用

void Player::sortPrint(int n, Player*)替换void Player::sortPrint(int n, Player arr[])并调用类似players->sortPrint(n, *players)的函数

你的问题是,players是指向Player数组的指针,数组没有包含者的成员函数。由于Player::sortPrint不依赖于对象本身,因此将其声明为 static 并像 Player::sortPrint(n, players); 一样调用它

除非你有很好的理由不这样做,否则你应该使用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();
    }
}

(或者,您可以在Player类上定义一个比较分数的operator<,这将允许您将玩家存储在std::setstd::map中。