Download

How do I avoid querying every array twice?

This is likely super-dumb of me, but I’ve been finding myself using the same pattern over and over when I want to modify an array index; given a TArray of some arbitrary struct FMyStruct, I always end up doing the following:



		TArray<FMyStruct> structArray;
		FMyStruct specificStruct;

		if (structArray.Contains(specificStruct)) { //Verify array contains desired struct
			structArray[structArray.Find(specificStruct)].DoStuff; //Locate the index of that struct, and use it
		}

This works, but it’s super-duper inefficient because I’m searching the array twice, once with Contains() and once with Find(). Is there a way I can just get the array directly from TArray::Contains(), so I don’t have to run two checks every time I try to access an index?

You could use find and then check the return value is not “INDEX_NONE”, Then do it.

Like so:



//Locate the index of that struct, and use it
const auto index = structArray.Find(specificStruct);

//Verify array contains desired struct
if ( INDEX_NONE != index ) 
	structArray index ].DoStuff; 


Ooh that’s a really good idea, thank you!! :slight_smile:

Your welcome :slight_smile: