从我的TArray of structs.My结构中删除结构有点困难,它包含AudioComponent和float.I,我使用的是Array.RemoveAt(索引),但是我从中得到的只是删除了结构的一半,即AudioComponent。为什么会这样呢?我的函数删除元素如下所示:
void RemoveArrayElement( UAudioComponent AudioComponent )
{
for( int i=0; i<Array.Num(); i++ )
{
if( AudioComponent == Array[i].AudioComponent )
{
Array.RemoveAt( i );
}
}
}我想要实现的是完全删除索引,AudioComponent和它的浮动。
发布于 2017-05-23 15:07:09
您的代码几乎没有问题。正如注释中提到的,您应该使用指针。如果我没弄错的话,你不能用这样的建筑:
UPROPERTY()
TArray<UAudioComponent> invalidArray;您应该使用UPROPERTY宏,否则您的属性可能而且可能会被垃圾收集。UPROPERTY wiki。
接下来的事情是,您正在更改正在迭代的数组。我写了一些方法,让我们看看它们:
void RemoveArrayElement(UAudioComponent* AudioComponent)
{
TArray<UAudioComponent*> audioArray; // array will be initialized somewhere else, this is for demo purpose.
// you always should check your pointers for validity
if (!AudioComponent || !AudioComponent->IsValidLowLevel() || AudioComponent->IsPendingKill())
return;
// Correct approach 1 (multiple):
TQueue<UAudioComponent*> toDelete;
for (int i = 0; i < audioArray.Num(); i++)
{
auto item = audioArray[i];
if (AudioComponent == item || true) // we simulate another condition for multiselect
{
toDelete.Enqueue(item);
}
}
// better approach for iteration:
for (auto item : audioArray)
if (item == AudioComponent || true) // we simulate another condition for multiselect
toDelete.Enqueue(item);
// finalize deletion in approach 1
UAudioComponent* deleteItem;
while (toDelete.Dequeue(deleteItem))
audioArray.Remove(deleteItem);
// almost correct approach 2 (single) :
UAudioComponent* foundItem;
for (auto item : audioArray)
if (item == AudioComponent)
{
foundItem = item;
break; // we can skip rest - but we must be sure, that items were added to collection using AddUnique(...)
}
if (foundItem)
audioArray.Remove(foundItem);
// correct and the best - approach 3 (single)
audioArray.Remove(AudioComponent);
}发布于 2017-05-23 15:06:58
首先,请记住,比较两个对象并不一定会产生预期的平等结果。使用==运算符意味着执行指定应该发生什么的函数(bool operator==(L, R);)。因此,如果您没有重载==操作符,那么您就不知道使用它会导致什么结果,除非您查看定义它的源代码。由于您想要删除确切的音频组件,而不是它的一个看起来相同的实例,所以您希望在数组中使用指针。这也有助于性能,因为在调用RemoveArrayElement(...);时,您不是要复制整个组件,而是一个指针。另外,当数组中有两个相同的音频组件存储在索引a和a+1时,然后删除索引a处的音频组件,下一次迭代将跳过第二个音频组件,因为所有上层索引都会减少一个。
https://stackoverflow.com/questions/44136216
复制相似问题