TArray iteration

Is this iteration system correct?

Or is there a more efficient way to do the search?

/** @returns list of most important checkpoints of overlapped
 *
 * @param IgnoredCheckpoints		Checkpoints to exclude from search
 */
TArray<ADHCheckpoint*> ADHPawn::GetImportantCheckpoints(TArray<ADHCheckpoint*> IgnoredCheckpoitns) const
{
	TArray<ADHCheckpoint*> ReturnValue;
	int32 CurrentRecord = -1;

	int32 Counter, ArrayLength;
	for (Counter = 0, ArrayLength = OverlappedCheckpoints.Num(); Counter <= ArrayLength; Counter += 1)
	{
		bool bSkipIteration = false;

		int32 IgnoreCounter, IgnoreLength;
		for (IgnoreCounter = 0, IgnoreLength = IgnoredCheckpoitns.Num(); IgnoreCounter <= IgnoreLength; IgnoreCounter += 1)
		{
			bSkipIteration = bSkipIteration || (OverlappedCheckpoints[Counter] == IgnoredCheckpoitns[IgnoreCounter]);
		}

		if (!bSkipIteration && (OverlappedCheckpoints[Counter]->CheckpointImportance >= CurrentRecord))
		{
			CurrentRecord = OverlappedCheckpoints[Counter]->CheckpointImportance;
			ReturnValue.AddUnique(OverlappedCheckpoints[Counter]);
		}
	}

	// Re-using iteration counters here is totally fine
	for (Counter = 0, ArrayLength = ReturnValue.Num(); Counter <= ArrayLength; Counter += 1)
	{
		if (ReturnValue[Counter]->CheckpointImportance < CurrentRecord) ReturnValue.Remove(ReturnValue[Counter]);
	}

	return ReturnValue;
}

Thanks for the answer, but I put in int32 ArrayLength as a failsafe for mid-iteration value change of Num()

Cool, it works :smiley:

It should be like this, remeber that size or array is bigger by 1 then maximum index, sho you should not use <=, you also as you can see you dont need to declere varabels needed in loop

int32 Size = ReturnValue.Num();
for(int32 Counter = 0; Counter < Size; Counter++)

But there a lot nicer way in C++11 (which newest compilers supports and UE4 actully require it) it’s like foreach :slight_smile:

for(ADHCheckpoint* Check : ReturnValue) {
    if (Check->CheckpointImportance < CurrentRecord) ReturnValue.Remove(Check)
}

It works on anyobject that implements standard C++ iterator (begin(), end(), ++ and * operators), which TArray and other containers in UE4 does. But this should not be used with item remove

Oh that might be a issue with that Remove indeed, but try 2nd solution it uses iterator in TArray insted of standard loop

Removing while using a ranged-for-loop will likely work as expected with TArray, but it is actually undefined behaviour. UE4 will trigger a breakpoint if in debug mode complaining about array has changed while iteration.

You right i actully that recently too, but first option should work if you save ReturnValue.Num() beforehand. i will edit anwser