How to iterate a TMap

Hi im following a book called “learning c++ by creating games with UE4” and i can’t handle this map. I decalred a TMap in Avatar.h

The map is meant to be an inventory:

TMap<FString, int> Backpack;

then when trying to iterate the map in Avatar.cpp

    for (TMap<FString, int>::TIterator it = Backpack.CreateIterator(); it; it++)
    
    	{
    		FString fs = it->Key + FString::Printf(TEXT("x %d"), it->Value);
    		UTexture2D* tex;
    		if (Icons.Find(it->Key))
    			tex = Icons[it->Key];
    		hud->addWidget(Widget(Icon(fs, tex)));
    	}

I get the following error:
"
F:\Unreal projects\MyProject2\Source\MyProject2\Avatar.cpp(96): error C2676: binary ‘++’: ‘TMapBase::TIterator’ does not define this operator or a conversion to a type acceptable to the predefined operator
with
[
KeyType=FString,
ValueType=int32,
SetAllocator=FDefaultSetAllocator,
KeyFuncs=TDefaultMapHashableKeyFuncs<FString,int32,false>
]

"

I cant find a solution and its killing me.

1 Like

Try auto and see value type:

for (auto& Elem : FruitMap)
{
    FPlatformMisc::LocalPrint(
        *FString::Printf(
            TEXT("(%d, \"%s\")\n"),
            Elem.Key,
            *Elem.Value
        )
    );
}



//or this 
   for (auto It = FruitMap.CreateConstIterator(); It; ++It)
    {
        FPlatformMisc::LocalPrint(
            *FString::Printf(
                TEXT("(%d, \"%s\")\n"),
                It.Key(),   // same as It->Key
                *It.Value() // same as *It->Value
            )
        );
    }
1 Like

Thanks, it worked!!

For TMap you need to use
++it
and not
it++

Do not forget about UE4 Coding Standard, solution for TMap:

https://docs.unrealengine.com/en-US/Programming/Development/CodingStandard/index.html#range-basedfor

It.Key()/It.Key are the same but in this instance you must include the brackets or you can not access anything at the key/value.