What is the most safe way to iteration remove TMap.

Hello. What i know about iteration remove TMap like 1. accumulation remove TMap::Key list 2.Iteration remove list actual remove each items. But I want to know move simple and safe way to iteration remove. Thanks.

Well its been more then a year no one knows ???

I think you want to iterate a container and remove along the way? A common way is to just iterate backwards:


for(int i=myContainer.Length-1; i>=0; i--)
{
    if(something)
    {
        myContainer.RemoveAt(i);
    }
}

FYI: While loops also can be used to iterate forwards, but in truth there isn’t a great way. The problem with index based looping and TMaps is you can’t access a Key/Value pair by it’s index so it’s difficult to perform any type of conditional testing inside the loop. If at all possible, I’d manage a stale list of keys when doing “other” processing on the TMap and clean out the stale list at the end. But if you need to iterate over it. Assuming you have the following TMap:



  TMap<FName, FString> TestMap;


You can do the following:




    TArray<FName> MyKeys;
    TestMap.GetKeys(MyKeys);
    for (FName Key : Keys)
    {
        if (Key == FName(TEXT("DeleteKey"))
        {
            TestMap.Remove(Key);
        }
    }
    TestMap.Compact();



That allows you to remove pairs from the TMap while still being able to use the TMap for testing/etc. But yea, sucks that you have to pull the keys to a secondary array. Oddly enough since removes from a TMap are soft until the TMap is Compacted, I think the iterator could be adjusted to allow for it in the case of a TMap. But since I almost never run in to this I’m not going to do it.

2 Likes

For maps you likely need to use the iterator as I’m not sure you can use “RemoveAt” for them. However, iterators have an aptly named “RemoveCurrent” method which will remove that key/value pair from the map.




TMap<FName, UObject*> MyMapOfStuff;
For(TMap<FName, UObject*>::Iterator ItRemove = MyMapOfStuff.CreateIterator(); ItRemove; ++ItRemove)
{
   // If I want to remove the current pair for whatever reason.
   ItRemove.RemoveCurrent();
}



4 Likes

I think this is the most efficient and safe way to deletion during iteration time to TMap. Thanks your reply.

Hmm, I didn’t know Iterators had a RemoveCurrent() function. I’ll have to play with that. But that does actually seem like a smoother way to do this. But I’m wondering if it does pretty much the same thing under the hood. I’ve never looked at the actual TMap implementation.

With fixed typo:

		TMap<FName, UObject*> MyMapOfStuff;
		for (TMap<FName, UObject*>::TIterator ItRemove = MyMapOfStuff.CreateIterator(); ItRemove; ++ItRemove)
		{
			// If I want to remove the current pair for whatever reason.
			ItRemove.RemoveCurrent();
		}