TMap, TArray, TSet containers in Unreal Engine 5 C++

Written on: 15 January 2025


TMap

// Creating
TMap<int, FString> MyMap = {
    {1, TEXT("Item 1")},
    {2, TEXT("Item 2")},
    {3, TEXT("Item 3")}
};


// Getting
FString MyValue = MyMap[2];           // Will cause crash if not in map
FString* MyValuePtr = MyMap.Find(3);  // Will return nullptr if not in map


// Setting
MyMap[2] = TEXT("New Item 2");


// Adding
MyMap.Add(4, TEXT("Item 4"));


// Removing
MyMap.Remove(2);


// Emptying
MyMap.Empty(); // or MyMap.Reset()


// Checking
bool bHasKey = MyMap.Contains(5);


// Counting
int32 MyCount = MyMap.Num();


// Iterating
for (auto& Elem : MyMap) {
    int Key = Elem.Key;
    FString Value = *Elem.Value;
}

for (auto It = MyMap.CreateConstIterator(); It; ++It) {
    int Key = It.Key();           // Or It->Key
    FString Value = *It.Value();  // Or *It->Value
}


// Creating Array of Keys
TArray<int> MyMapKeys;
MyMap.GenerateKeyArray(MyMapKeys);


// Creating Array of Values
TArray<FString> MyMapValues;
MyMap.GenerateValueArray(MyMapValues);

TArray

// Creating
TArray<FString> MyArray = {
    TEXT("Item 0"),
    TEXT("Item 1"),
    TEXT("Item 2"),
    TEXT("Item 3")
};


// Getting
FString MyItem = MyArray[2];                     // Will cause crash if not in array so check first
int MyItemIndex = MyArray.Find(TEXT("Item 1"));  // Will return INDEX_NONE if not in array


// Setting
MyArray[2] = TEXT("New Item 2");


// Adding
MyArray.Add(TEXT("Item 4"));                // Adds at the end
MyArray.Insert(TEXT("Item in middle"), 2);  // Adds at given index


// Removing
MyArray.Remove(TEXT("Item 1"));        // Finds and removes all matching items
MyArray.RemoveSingle(TEXT("Item 2"));  // Finds and removes single matching item
MyArray.RemoveAt(2);                   // Removes Item at given index, will cause crash if does not exist


// Emptying
MyArray.Empty();


// Checking
bool bHasItem = MyArray.Contains(TEXT("Somet"));


// Counting
int MyCount = MyArray.Num();


// Iterating
for (auto& Elem : MyArray) {
}

for (int Index = 0; Index != MyArray.Num(); ++Index) {
    auto Item = MyArray[Index];
}


// Sorting
MyArray.Sort([](const FString& A, const FString& B) {
    return A.Len() < B.Len();
});

TSet

// Creating
TSet<FString> MySet = {
    TEXT("Item 1"),
    TEXT("Item 2"),
    TEXT("Item 3"),
    TEXT("Item 4"),
};


// Adding
MySet.Add(TEXT("Item 5"));


// Removing
MySet.Remove(TEXT("Item 2"));


// Emptying
MySet.Empty();  // or MySet.Reset()


// Checking
bool bHasItem = MySet.Contains(TEXT("Item 2"));


// Counting
int MyCount = MySet.Num();


// Iterating
for (auto& Elem : MySet) {
}

for (auto It = MySet.CreateConstIterator(); It; ++It) {
    auto Item = *It;
}