TSet整体介绍
- TSet 类似于 TMap 和 TMultiMap
- TSet 可以非常快速地添加、查找和删除元素(O(1))
- 默认情况下TSet 不支持重复的键
- 键类型也必须是值类型
- TSet 内部的元素相对排序既不可靠也不稳定
构造和添加元素
- 可预先申请内存
- 优先使用Emplace,减少创建临时对象
- Append 可插入集合,容器
TSet<int32> IntSet;
IntSet.Reserve(10); // 预先申请
IntSet.Add(1);
IntSet.Add(3);
IntSet.Add(2);
IntSet.Add(2); // 只保留1个2
IntSet.Emplace(4); // 避免创建临时文件 比如FString
IntSet.Emplace(5);
IntSet.Emplace(6);
IntSet.Append({7,8,9}); // 可插入Set
查询和删除
- Num查询数量
- Contains 和 Find 返回值和指针
- Remove返回为删除的数量!
// 获取数量
UE_LOG(TestLog, Log, TEXT("IntSet.Num() = %d"), IntSet.Num());
// 获取内存使用量
UE_LOG(TestLog, Log, TEXT("IntSet.GetAllocatedSize () = %d"), IntSet.GetAllocatedSize());
// 查询
bool bHas2 = IntSet.Contains(2);
bool bHas20 = IntSet.Contains(20); // false
int32* Ptr5 = IntSet.Find(5);
int32* Ptr50 = IntSet.Find(50); // nullptr
// 获取数组
auto NumArray = IntSet.Array();
// 删除
int32 NumRet = IntSet.Remove(8); // 返回删除的数量!
NumRet = IntSet.Remove(8); // 返回0
排序和遍历
// 排序
IntSet.Sort([](const int32& A, const int32& B)
{
return A > B;
});
// 遍历
for(auto& elem :IntSet)
{
UE_LOG(TestLog, Log, TEXT("elem = %d"), elem);
}
// 迭代器
for(auto it = IntSet.CreateConstIterator(); it; ++it)
{
UE_LOG(TestLog, Log, TEXT("*it =%d"), *it);
}
删除和内存整理
IntSet.Remove(1);
IntSet.Remove(3); // 导致内存存储为稀疏状态
IntSet.Shrink(); // 只删除尾部空闲
IntSet.Compact(); // 整理后内存连续,无中空
IntSet.Shrink();
网友评论