Announcement

Collapse
No announcement yet.

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

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    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:

    Code:
    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: https://www.unrealengine.com/en-US/b...ased-for-loops

    #2
    Iterating tArray by index on this page:

    https://docs.unrealengine.com/en-US/...ays/index.html

    As for "best way" it heavily depends on use case.

    Comment


      #3
      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.

      Comment


        #4
        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.

        Comment

        Working...
        X