This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center。
7年前关闭。
我的代码有问题,我想知道是否有人可以看一下,我有一个函数可以删除数组中的特定元素。我使用线性搜索来查找元素,然后用之后的元素覆盖要删除的元素,因为我还没有找到一种专门删除元素的方法。我的问题是代码不会真正起作用,因为元素不会被覆盖,一旦元素被覆盖,还有没有办法在数组中保留空白。
下面是我的代码:
现在为您擦除:
这个小片段不会“复制”整个对象,而是将它们向上移动到数组中(无需重建任何对象)。
当您遇到第一个NULL指针(并且最晚MAX_PLAYERS)时,该数组位于其“末端”,这说明您的“空白空间”。或者,您可以省略“向上移动”,而只是销毁对象并将指针设置为NULL。这样,您就会知道那里没有球员。
7年前关闭。
我的代码有问题,我想知道是否有人可以看一下,我有一个函数可以删除数组中的特定元素。我使用线性搜索来查找元素,然后用之后的元素覆盖要删除的元素,因为我还没有找到一种专门删除元素的方法。我的问题是代码不会真正起作用,因为元素不会被覆盖,一旦元素被覆盖,还有没有办法在数组中保留空白。
下面是我的代码:
void deleteinfo()
{
string search ;
int found ;
cout << "\n Delete A Player's Information \n\n" ;
cout << "Please Enter The Player's Last Name : " ;
cin >> search ;
found=linsearch(search);
if (found==-1)
{
cout << "\n There is no player called " << search ;
}
else
{
player[found].getFirstName() = player[found + 1].getFirstName() ;
player[found].getLastName() = player[found + 1].getLastName() ;
player[found].getAge() == player[found + 1].getAge() ;
player[found].getCurrentTeam() = player[found + 1].getCurrentTeam() ;
player[found].getPosition() = player[found + 1].getPosition() ;
player[found].getStatus() = player[found + 1 ].getStatus() ;
cout << "\n Player has been deleted." ;
}
cin.get() ;
menu() ;
}
int linsearch(string val)
{
for (int j=0; j <= 3; j++)
{
if (player[j].getLastName()==val)
return j ;
}
return -1 ;
}
最佳答案
这只是一个示例,您可能如何解决此问题。我假设您有一个静态长度数组(最大玩家数)。
Player *Players[MAX_PLAYERS]; //Array with pointers to Player objects.
for(int i = 0; i < MAX_PLAYERS; ++i)
Players[i] = new Players(x, y, z); //Fills the array with some data.
现在为您擦除:
if(found > 0) {
delete Players[found]; //Destroys the object in question.
for(int i = found; i < MAX_PLAYERS - 1; ++i)
Players[i] = Players[i + 1]; //Moves the entire list up by one.
Players[MAX_PLAYERS - 1] = NULL; //Marks the new end of the list.
}
这个小片段不会“复制”整个对象,而是将它们向上移动到数组中(无需重建任何对象)。
当您遇到第一个NULL指针(并且最晚MAX_PLAYERS)时,该数组位于其“末端”,这说明您的“空白空间”。或者,您可以省略“向上移动”,而只是销毁对象并将指针设置为NULL。这样,您就会知道那里没有球员。
关于c++ - 删除存储在数组中的特定类对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14485780/