C++按属性排序的对象动态数组
C++ Dynamic Array of Objects Sorting by Property
我正在尝试将选择排序实现为类中的成员函数,以对类的对象进行排序,其中玩家总数是通过用户输入获得的,也是由用户获取的玩家姓名和分数。
我将按玩家分数的属性对玩家对象进行排序,该分数是一个类成员,由用户输入获取。
我的问题是,我卡在 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::set
或std::map
中。
相关文章:
- C++中的动态对象与非动态对象
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 生成文件:动态源文件名和对象目录
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 使用动态实例化的对象填充矢量的快速方法
- 如何在 Cheerp/js 中迭代动态命名的对象?
- 销毁C++中动态分配的内存(数组对象)
- 创建动态对象并将其推送到矢量中
- 删除包含包含动态对象的 STL 容器的智能指针
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何访问对象动态数组中的私有成员变量?
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- Cython 中对象动态大小的数组
- malloc分配的对象动态类型是什么
- C++按属性排序的对象动态数组
- visual C++新与Malloc的对象动态内存阵列