[英]Deleting an element from an array of objects
I tried to write a function that gets an object ("Stone") and deletes the stone from a given array. 我试图编写一个获取对象(“石头”)并从给定数组中删除石头的函数。 code: 码:
void Pile::del_stone(Stone &s)
{
Stone *temp = new Stone[size - 1];//allocate new array
for (int i = 0;i <size;++i)
{
if (s != Pile_arr[i])//if the given object to delete is different from the current
{
temp[i] = Pile_arr[i];//copy to the new array
}
else
{
i--;
}
}
Pile_arr = temp;
set_size(this->size - 1);
temp = NULL;
delete[] temp;
}
Pile_arr is a member of Pile class. PILE_ARR是PILE类的成员。 The problem is that i get an infinite loop, because i decrease i. 问题是我得到无限循环,因为我减少了我。 I cant figure out how to solve this issue. 我不知道如何解决这个问题。 Any ideas? 有任何想法吗?
Use two indexes: i and j. 使用两个索引:i和j。 Use i to know which element of the original array you are looking and j to know where to put the element in temp. 使用i知道您要查找原始数组的哪个元素,使用j知道将元素放入temp的位置。
You need to use a separate counter to track where new elements should be placed. 您需要使用一个单独的计数器来跟踪新元素的放置位置。 I have used n
below: 我在下面使用了n
:
Stone *temp = new Stone[size - 1];
int n = 0; // Stores the current size of temp array
for (int i = 0;i <size;++i) {
if (s != Pile_arr[i]) {
temp[n++] = Pile_arr[i];
}
}
It's also worth considering the case where s
is not found in the array, as this would cause a runtime error (Attempting to add size
elements to an array of size size - 1
). 还值得考虑在数组中未找到s
的情况,因为这会导致运行时错误(尝试将size
元素添加到size - 1
的数组中)。
Using a STL container would be a far better option here. 在这里使用STL容器将是更好的选择。
This function will: 该功能将:
First of all, this function is bad for 3 reasons: 首先,此功能不好有以下三个原因:
If the object is not immediately found, the array will get stuck, as you decrease the index, and then increase it using the loop--you'll never move again. 如果没有立即找到对象,则在减小索引然后使用循环增大索引时,数组将被卡住-您将再也不会移动。
Stone *temp = new Stone[size - 1];//allocate new array for (int i = 0;i Stone * temp = new Stone [size-1]; //为(int i = 0; i
Instead: 代替:
temp = found object
Copy temp_array[i] and increment i if and only if temp_array[j] is not marked/deleted. Increment j
Once again, you can decide to use separate indexes--one for parsing the original array, and one for filling the new array. 再一次,您可以决定使用单独的索引-一个用于解析原始数组,另一个用于填充新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.