Download

How to best obtain the index when iterating through a TArray?

I have this array: TArray<FQuestInfo> QuestList;

If I am iterating through it in this manner:


int32 AQuestManager::GetQuestIndex(FName questID)
{
    for (FQuestInfo& quest : QuestList)
    {
        if (quest.QuestID == questID)
        {
            return // need to return index of iterator here
        }
        else
        {
            return -1;
        }
    }
}

How do I obtain the index with this method of iteration? Or is it just necessary to use a different method?

If so, can anyone recommend me the best/most efficient way to iterate through a TArray to be able to both get the indices if needed, or perform action on the items in the array?

I found this method on this UE4 blog that’s dated 2014: Range-Based For Loops - Unreal Engine

Iterating tArray by index on this page:

As for “best way” it heavily depends on use case.

Thanks, I saw that page as well earlier. Will make sure I bookmark it for future reference. I suppose that in this case, a regular old for loop is probably the best option based on my use case.

The point of a for-each loop is that you don’t care about index. If you need the index, use an index-based for loop.

You can also use IndexOfByPredicate() for your use-case, which internally is basically the same thing.