删除存储在数组中的特定类对象

Deleting specific class objects stored in an array

本文关键字:对象 存储 数组 删除      更新时间:2023-10-16

我的代码有问题,我想知道是否有人可以看看,我创建了一个函数来从数组中删除特定元素。我使用线性搜索来查找元素,然后用后面的元素覆盖要删除的元素,因为我还没有找到专门删除元素的方法。我的问题是代码并没有真正起作用,因为元素不会被覆盖,一旦元素被覆盖,也有办法在数组中留下空格。

下面是我的代码:

void deleteinfo()
{
    string search ;
    int found ;
    cout << "n Delete A Player's Information nn" ;
    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。这样,你就会知道,那里没有球员。

你要做的是将要删除的元素后面的所有元素复制到左边的一个位置,最后更新数组的新长度。例如:

for (size_t i = found + 1; i < player_length; ++i) {
    player[i - 1] = player[i];
}
--player_length;

player数组中的对象必须是可复制的。我假设你在某处有一个变量来保存数组的当前长度("长度"是指它当前有多少玩家,而不是它的总容量。