TMap 也是是虚幻引擎中最常用的容器类。与TArray很相似,不过TMap是以键值对<Key, Value>的形式存在的。
1、创建
TMap<int32, FString> FruitMap;
2、填充数据
Add 和 Emplace
填充Map的标准方式是使用 Add 函数:
FruitMap.Add(5, TEXT("Banana"));
FruitMap.Add(2, TEXT("Grapefruit"));
FruitMap.Add(7, TEXT("Pineapple"));
// FruitMap == [
// { Key:5, Value:"Banana" },
// { Key:2, Value:"Grapefruit" },
// { Key:7, Value:"Pineapple" }
// ]
虽然这里我们是按(5、2、7)这样的顺序填充的数据,但无法保证这些元素就是按照这样的顺序排列,因为 TMap 是无序的。
TMap 的 Key 是唯一的,当我们添加一个已经存在的 Key 时,它会覆盖原有的 Value :
FruitMap.Add(2, TEXT("Pear"));
// FruitMap == [
// { Key:5, Value:"Banana" },
// { Key:2, Value:"Pear" },
// { Key:7, Value:"Pineapple" }
// ]
TMultiMap 的 Key 不是唯一的,可以多次添加同一个 Key 的 <Key, Value>。
当我们调用 Add 时,只传入参数 Key,不传 Value 的话,会使用 Value 的默认构造函数来创建对象:
FruitMap.Add(4);
// FruitMap == [
// { Key:5, Value:"Banana" },
// { Key:2, Value:"Pear" },
// { Key:7, Value:"Pineapple" },
// { Key:4, Value:"" }
// ]
与 TArray 一样,也可以使用 Emplace 来避免添加过程中创建临时变量:
FruitMap.Emplace(3, TEXT("Orange"));
// FruitMap == [
// { Key:5, Value:"Banana" },
// { Key:2, Value:"Pear" },
// { Key:7, Value:"Pineapple" },
// { Key:4, Value:"" },
// { Key:3, Value:"Orange" }
// ]
Append
同 TArray 一样,我们可以使用 Append 来一次性添加多个元素:
TMap<int32, FString> FruitMap2;
FruitMap2.Emplace(4, TEXT("Kiwi"));
FruitMap2.Emplace(9, TEXT("Melon"));
FruitMap2.Emplace(5, TEXT("Mango"));
FruitMap.Append(FruitMap2);
// FruitMap == [
// { Key:5, Value:"Mango" },
// { Key:2, Value:"Pear" },
// { Key:7, Value:"Pineapple" },
// { Key:4, Value:"Kiwi" },
// { Key:3, Value:"Orange" },
// { Key:9, Value:"Melon" }
// ]
相当于使用 Add/Emplace 逐个添加,同样会覆盖已存在的键值对。
3、遍历
遍历 TMap 与遍历 TArray类似。
使用C++的 ranged-for’:
for (auto& Elem : FruitMap)
{
UE_LOG(LogClass, Log, TEXT("Key: %d Value: %s"), Elem.Key, *Elem.Value);
}
// Output:
//Key: 5 Value : Mango
//Key: 2 Value : Pear
//Key: 7 Value : Pineapple
//Key: 4 Value : Kiwi
//Key: 3 Value : Orange
//Key: 9 Value : Melon
使用迭代器 CreateIterator 或 CreateConstIterator :
for (auto It = FruitMap.CreateConstIterator(); It; ++It)
{
UE_LOG(LogClass, Log, TEXT("Key: %d Value: %s"), It.Key(), *It.Value());
}
// Output:
//Key: 5 Value : Mango
//Key: 2 Value : Pear
//Key: 7 Value : Pineapple
//Key: 4 Value : Kiwi
//Key: 3 Value : Orange
//Key: 9 Value : Melon
4、查询相关
Num 函数获取TMap保存的元素数量:
int32 Count = FruitMap.Num();
// Count == 6
与访问TArray类似,我们可以使用Key的索引来获取对应的Value:
FString Val7 = FruitMap[7];
// Val7 == "Pineapple"
//FString Val8 = FruitMap[8]; // assert!
如果对应的 <Key, Value>不存在,则会触发运行时断言。
使用 Contains 函数检查 TMap 中是否存在特定键:
bool bHas7 = FruitMap.Contains(7);
bool bHas8 = FruitMap.Contains(8);
// bHas7 == true
// bHas8 == false
通常我们可以使用 **操作符“[ ]” 或 Contains 函数来查找 TMap 是否存在某个 Key,但这不是最优的,因为它们会对 Key 进行两次查找。而 Find 函数只执行一次查找,返回的是指向元素的指针,若不存在则返回 null :