是否一定要使用TMap?
通常情况下,TArray可以应对90%的情况。
如果需要频繁查找,并且是在大量数据中(超过100个,其实我想说10000个),才考虑使用TMap。
基本上,只有一种情况可能会使用数组:
常量数组
例如:
FString strVec[2] = {"aa", bbb"};
int32 num = ARRAY_COUNT(strVec); //使用宏ARRAY_COUNT统计数组里的个数
其他情况,请考虑使用容器。
1.
增加:
1.1
增加新元素
TMap<int32, FString> FruitMap;
FruitMap.Add(5, TEXT("Banana"));
1.2
预留多元素位置
FruitMap.Reserve(10);
for (int32 i = 0; i < 10; ++i)
{
FruitMap.Add(i, FString::Printf(TEXT("Fruit%d"), i));
}
说明:
如果数组能预先知道元素数量,并且元素数量为大量(超过32个),并且单元素的体积比较大时,可以考虑使用Reserve()。
2.
删除:
2.1
删除
FruitMap.Remove(8);
2.2
清空
FruitMapCopy.Empty();
3.
修改:
3.1
直接访问
TMap<int32, FString> NewMap = FruitMap;
NewMap[5] = "Apple";
NewMap.Remove(3);
// FruitMap == [
// { Key:4, Value:"Kiwi" },
// { Key:5, Value:"Mango" },
// { Key:9, Value:"Melon" },
// { Key:3, Value:"Orange" }
// ]
// NewMap == [
// { Key:4, Value:"Kiwi" },
// { Key:5, Value:"Apple" },
// { Key:9, Value:"Melon" }
// ]
4.
查询:
4.1
遍历
for (TPair<int32, FString>& element : _map)
{
UE_LOG(MyContaimTest, Warning, TEXT("--- key:%d, value111:%s "), element.Key, *element.Value);
}
说明:
如果一定要遍历TMap才能达到目的,而不是TMap的Find()或使用TArray进行遍历,这时需要考虑一下数据结构的合理性。
4.2
查找
FString* Ptr7 = FruitMap.Find(7);
FString* Ptr8 = FruitMap.Find(8);
// *Ptr7 == "Pineapple"
// Ptr8 == nullptr
参考:
1.
《TMap》
https://docs.unrealengine.com/zh-CN/Programming/UnrealArchitecture/TMap/index.html
2.
《UE4容器TArray、TMap的使用》
https://blog.csdn.net/yangxuan0261/article/details/52078303/