Fork me on GitHub

关于 UE4 TMap 的几种遍历方式

测试数据

1     TMap<int32, FString> Map1;
2     TMap<int32, FString> Map2;
3 
4     Map1.Add(1, TEXT("AAA"));
5 
6     ShowMap_1(Map1, 1);
7     ShowMap_2(Map1, 1);
8     ShowMap_3(Map1, 1);

 

 

1. 通过 Key 直接查找 Map

 1     // 通过 Key 直接查找 Map
 2     auto ShowMap_1 = [](const TMap<int32, FString> Value, int32 Key)->void
 3     {
 4         if (Value.Contains(Key))
 5         {
 6             UE_LOG(LogTemp, Display, TEXT("Key is %d value is: %s"), Key, *Value[Key]);
 7         }
 8         else
 9         {
10             UE_LOG(LogTemp, Display, TEXT("Key %d is error"), Key);
11         }
12     };

 

1     // 调用
2     ShowMap_1(Map1, 1);
3     ShowMap_1(Map1, 2);

 

 

2. 通过 Find 查找 Map

 1 auto ShowMap_2 = [](const TMap<int32, FString> Value, int32 Key)->void
 2     {
 3         if (Value.Contains(Key))
 4         {
 5             const FString* Vall = Value.Find(Key);
 6             if (Vall != nullptr)
 7             {
 8                 UE_LOG(LogTemp, Display, TEXT("Key is %d value is: %s"), Key, Vall->operator*());
 9             }
10             else
11             {
12                 UE_LOG(LogTemp, Display, TEXT("Key %d Ptr error"), Key);
13             }
14         }
15         else
16         {
17             UE_LOG(LogTemp, Display, TEXT("Key %d is error"), Key);
18         }
19     };

 

1     // 调用
2     ShowMap_2(Map1, 1);
3     ShowMap_2(Map1, 2);

 

 

 

3. 通过 FindRef 查找 Map

 1     auto ShowMap_3 = [](const TMap<int32, FString> Value, int32 Key)->void
 2     {
 3         if (Value.Contains(Key))
 4         {
 5             const FString Vall = Value.FindRef(Key);
 6             if (&Vall != nullptr)
 7             {
 8                 // UE_LOG(LogTemp, Display, TEXT("Key is %d value is: %s"), Key, *Vall);     两种方式都可以
 9                 UE_LOG(LogTemp, Display, TEXT("Key is %d value is: %s"), Key, Vall.operator*());
10             }
11             else
12             {
13                 UE_LOG(LogTemp, Display, TEXT("Key %d Ptr error"), Key);
14             }
15         }
16         else
17         {
18             UE_LOG(LogTemp, Display, TEXT("Key %d is error"), Key);
19         }
20     };

 

1     // 调用
2     ShowMap_3(Map1, 1);
3     ShowMap_3(Map1, 2);

 

 

posted @ 2023-05-14 22:57  索智源  阅读(993)  评论(0编辑  收藏  举报