Array has changed during ranged-for iteration!?

what is the cause of this breakpoint? Currently my array has the size = [100] and returned this error on beginplay… but if I increase the size to = [200] everything works fine.

Ensure condition failed: Lhs.CurrentNum == Lhs.InitialNum [[Source\Runtime\Core\Public\Containers/Array.h] [Line: 216]]
Array has changed during ranged-for iteration!

FDebug::EnsureFailed -  0.000000 s

This is caused by modifying an array during a for each loop for example, you don’t want to add/remove elements during the iteration. What are you trying to do exactly ? if you can post your code I can suggest an alternative way.

2 Likes

Thank you for reply Sir, this is 300 lines of code, looping through all items and if found anything , adding to the array and then from array spawning the item, everything works fine.

the problem starts when I try to randomize the array before spawning items.

Item = Arr[FMath::RandRange(0, Arr.Num() - 1)];

Item is the returning array with contain items to be spawned

I don’t think you will read all the 300 lines of code to get the things how are they implemented…

Your issue is probably modifying the array and letting the loop continue.
If you’re going to modify the array make sure you exit out of the loop after that using break or return.

I found that I already have a break in this loop where I am modifying the Array if the weapon is added, remove the first row which is not a weapon and add the corresponding ammo type of that weapon.

for (auto& Array : ItemsIDArr)
	{
		if (Array.Type != EItemType::E_Weapon)
		{
			ItemsIDArr.RemoveAt(1);
			break;
		}
	}

What about the shuffle ?

shuffle I am using like this.

FCustomThunkTemplates::Array_Shuffle(Arr);

I don’t really know to implement it without using blueprint library… but it works fine, it randomize the items fine if the array size is 200

Sir can you correct me about this bp script

image_2022-08-13_040431245

i have it like

if (i == -1) 
	{
		//some code
	}
else if (i != -1)
{
	//repeat some code
}

if this correct?

I’m just saying that shuffle also modify the array so make sure you stop the loop when you do that, similar to add/remove.

if (i == -1)
{
//some code
}
else if (i != -1)
{
//repeat some code
}

if this correct?

Apart from the redundant else if, repeating some code I would probably create a dedicated function for the task, and call it when you want to execute the same code again but maybe with different parameters.

if (i == -1)
{

}else //i not equal -1
{
	
}
2 Likes

thank you so much for assisting me :slight_smile:

1 Like

You can fix this from happening by just using a normal for loop instead of a ranged for:

int n = array.Num();
for(int i = 0; i < n; i++)
{

}