Change key in the TMap

How can I change the key value in TMap, C++?
I am trying to get all the keys using TMap::GetKeys, in the parameter I set a pointer to the key type inside TMap, but when changed, only the pointer changes.

This worked for me (using FStrings as keys):

bool RenameItem(FString OldKey, FString NewKey)
{
	if (!Items.Contains(OldKey) || Items.Contains(NewKey))
		return false;

	auto v = Items[OldKey]]; // Store the current value
	Items.Remove(OldKey);    // Get rid of the old key (and it's value)
	Items.Shrink();
	Items.Add(NewKey, v);    // Re-add the stored value using the new key

	return true;
}

What if we need to retain the order of the key/value pairs in the map? The only way I can think of is to loop through each pair and change the key directly, but not really sure if it is a good approach.

for (auto& pair : yourTMap)
{
	if (pair.Key == keyToReplace)
	{
		pair.Key = FString("new key value");
		break;
	}
}

EDIT:
Although my approach would change the key, this would be useless since the new key is not hashed and it wouldn’t be possible to search the map with that key. Is there a way to re-hash the table after changing the key value?

In your code once you re-hash it the order will still change.

The nature of a hashmap is that elements are un-ordered. If your relies on its order then you’re doing something wrong.

If you absolutely need an “ordered map”, one way to implement it is using a linked list in conjunction with hashmap, and you traverse the linked list when you need ordered data.

1 Like