删除存储在数组中的特定类对象
Deleting specific class objects stored in an array
我的代码有问题,我想知道是否有人可以看看,我创建了一个函数来从数组中删除特定元素。我使用线性搜索来查找元素,然后用后面的元素覆盖要删除的元素,因为我还没有找到专门删除元素的方法。我的问题是代码并没有真正起作用,因为元素不会被覆盖,一旦元素被覆盖,也有办法在数组中留下空格。
下面是我的代码:
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
数组中的对象必须是可复制的。我假设你在某处有一个变量来保存数组的当前长度("长度"是指它当前有多少玩家,而不是它的总容量。
相关文章:
- C++ 在堆栈中包含多态属性的类对象存储
- 将对象存储为其基本虚拟类
- 将大型对象存储在无序映射中是否效率低下
- C++:将未知类型的对象存储为成员变量的类
- 按unique_pointer将传递的对象存储在地图中
- 如何将 c++ 类对象存储为数组?
- 将对象存储在 std::map 中
- 是否存在对象存储在其生存期内可能会更改的情况?
- 将不同类型的对象存储在容器中
- 将自定义可绘制对象存储在数组中会导致绘制时出现分割错误
- 我将如何在C++中文件处理对象(存储/导入)
- 将对象存储在C 中的2维Sprite矩阵中
- 将抽象派生类对象存储在基类向量中
- 将任意函数对象存储到类成员容器中,而无需知道其声明签名
- 如何使用向量将类对象存储在超载操作员中
- 适当的方法将对象存储在Std矢量中
- 将向量对象存储在共享指针投掷错误中
- 将多态对象存储在unordered_set中
- 为什么我可以将对象存储在大小不同的数组中
- 返回对象存储在哪里