UE-TMap
概述
先了解TSet,
再看TMap. 原理是一样的, 也是索引层+值层,
按照这个思路会很好理解, 剩下的就是维护这两个层的数据正确.
TMap是继承自TMapBase,
最终操作的也是其成员变量ElementSetType Pairs,
即TSet类型.
TMap将Element类型设置为typedef TPair<KeyType, ValueType> ElementType;,
即Pair类型.

重写BaseKeyFuncs, 实现TDefaultMapKeyFuncs,
自定义关键函数GetSetKey和Matches,
来进行获取Key和KeyHash以及比较等操作. 这样,
其Element内容就和整个类解耦了.
前向声明(ContainersFwd.h):

实现:

关键变量
从TMap的整体构建来看,
其所有函数都是对ElementSetType Pairs进行操作,
其实就是对TSet的封装.
1 | typedef TPair<KeyType, ValueType> ElementType; |
Find
详见TSet.Find.

FindOrAdd
先进行Find, 如果没Find到,
则进行Add, 返回Add结果.
Add最终调用的是TSet.EmplaceByHash.


从上述代码可以看出,
FindOrAdd比Find+Add少算一次KeyHash,
并且从使用方式上比Find+Add更简洁.
所以推荐使用FindOrAdd.
Contains
详见TSet.Contains.

Remove
详见TSet.Remove.

operator[]
其核心还是调用TSet.Find.
查询到Item.Value并且返回其引用, 进而可以直接进行操作.


问
TMap是否也需要定义GetTypeHash函数呢?
TSet和TMap都需要, 否则就会报错, 因为添加新元素和对比的时候, 需要调用该类型的GetTypeHash.