TArray, TMap & Strings
Unreal code doesn't use the standard library containers for anything reflected, and by convention rarely uses them at all. The engine has its own, which work with reflection, serialization, replication and the engine's allocators.
| Unreal | Standard C++ analogue | Notes |
|---|---|---|
TArray<T> |
std::vector<T> |
the workhorse; reflected; Num() instead of size() |
TMap<K, V> |
std::unordered_map<K, V> |
reflected (but not replicated) |
TSet<T> |
std::unordered_set<T> |
reflected |
TOptional<T>, TVariant<…> |
std::optional, std::variant |
not reflected |
TUniquePtr<T>, TSharedPtr<T>, TSharedRef<T>, TWeakPtr<T> |
unique_ptr, shared_ptr, weak_ptr |
non-UObject data only |
TFunction<…> |
std::function |
|
FString |
std::string (UTF-16/TCHAR) |
mutable text |
FName |
(interned string) | case-insensitive, cheap to compare and copy: tags, bone names, sockets |
FText |
(localized string) | anything a player reads |
TArray
TArray<TObjectPtr<AActor>> Enemies;
Enemies.Reserve(32);
Enemies.Add(Grunt); // copies the pointer in; returns the index
Enemies.AddUnique(Grunt); // no-op if already there (linear search)
Enemies.Emplace(Archer); // constructs in place (for structs)
for (AActor* Enemy : Enemies) { ... } // range-for works
if (Enemies.Contains(Grunt)) { ... }
int32 Index = Enemies.IndexOfByKey(Grunt); // INDEX_NONE (-1) if absent
TObjectPtr<AActor>* Near = Enemies.FindByPredicate([this](const AActor* A) { return A->GetDistanceTo(this) < 500.f; });
Enemies.RemoveAll([](const AActor* A) { return !IsValid(A); }); // erase-remove in one call
TArray<AActor*> ByName = GetEnemiesSnapshot();
ByName.Sort([](const AActor& A, const AActor& B) { return A.GetName() < B.GetName(); }); // note: references
Enemies.RemoveAt(2); // keeps order, shifts the rest down
Enemies.RemoveAtSwap(2); // moves the last element into the hole: O(1), order changes
Enemies.Empty(); // clears and frees; Reset() clears and keeps capacityTArray::Sort on an array of pointers passes references to the pointees to the predicate (it dereferences for you), which surprises everyone once. StableSort keeps the order of equal elements.
Removing while iterating
Removing from an array you're looping over skips elements. Loop backwards, collect then remove, or use RemoveAll. This model shows the three outcomes on a list of enemies where Grunt and Archer are dead.
#include <iostream>
#include <string>
#include <vector>
struct Enemy { std::string Name; bool Dead; };
void Print(const char* label, const std::vector<Enemy>& v) {
std::cout << label << ":";
for (const auto& e : v) std::cout << " " << e.Name;
std::cout << "\n";
}
int main() {
const std::vector<Enemy> start = {{"Grunt", true}, {"Archer", true}, {"Brute", false}, {"Mage", false}, {"Rogue", false}};
auto a = start; // forward loop with RemoveAt: buggy
for (size_t i = 0; i < a.size(); i++)
if (a[i].Dead) a.erase(a.begin() + i); // the next element slides into i and is skipped
Print("forward RemoveAt ", a);
auto b = start; // backward loop: correct
for (size_t i = b.size(); i-- > 0;)
if (b[i].Dead) b.erase(b.begin() + i);
Print("backward RemoveAt ", b);
auto c = start; // RemoveAtSwap, backward: correct, O(1) each, order changes
for (size_t i = c.size(); i-- > 0;)
if (c[i].Dead) { c[i] = c.back(); c.pop_back(); }
Print("backward Swap ", c);
auto d = start; // RemoveAll(predicate)
std::erase_if(d, [](const Enemy& e) { return e.Dead; });
Print("RemoveAll ", d);
}forward RemoveAt : Archer Brute Mage Rogue
backward RemoveAt : Brute Mage Rogue
backward Swap : Mage Rogue Brute
RemoveAll : Brute Mage Rogue
Use RemoveAtSwap (RemoveSwap, RemoveAllSwap) when order doesn't matter: a list of active projectiles, spawned enemies, pooled objects.
TMap
UPROPERTY(EditDefaultsOnly, Category = "Loot")
TMap<FName, int32> LootWeights; // editable in the Details panel as a key/value list
LootWeights.Add(TEXT("Potion"), 10); // overwrites if the key exists
int32& Coins = LootWeights.FindOrAdd(TEXT("Coin"));
Coins += 5;
if (const int32* Weight = LootWeights.Find(TEXT("Potion"))) // returns a pointer, nullptr if absent
{
UE_LOG(LogTemp, Log, TEXT("Potion weight %d"), *Weight);
}
for (const TPair<FName, int32>& Pair : LootWeights) { ... }
LootWeights.Remove(TEXT("Coin"));TMap iteration order is the order of insertion until you remove something, then it isn't guaranteed. Don't build gameplay logic on it. TMap and TSet also can't be replicated. For replicated lists use a TArray of structs (or a FFastArraySerializer for large ones).
FString, FName, FText
FString Msg = FString::Printf(TEXT("%s has %d HP"), *GetName(), Health); // * converts FString to const TCHAR*
FName Socket = TEXT("hand_r"); // cheap to compare: an index into a name table
FText Label = NSLOCTEXT("Arena", "Wave", "Wave {0}");
FText Shown = FText::Format(Label, FText::AsNumber(WaveIndex));- Always wrap literals in
TEXT("…")so they become wideTCHARstrings on every platform. %sinPrintf/UE_LOGexpects aTCHAR*, so pass*MyString. Passing theFStringitself is a compile error, or, through some variadic paths, a crash.- Player-facing text is
FTextso it can be localized.FStringfor player-visible text is a bug that shows up the day you translate the game.
Test yourself
Which TArray function removes an element in O(1) by moving the last element into its place?
- RemoveAt
- RemoveAtSwap
- Empty
- Pop
What does TMap::Find return when the key is missing?
- A default value
- nullptr
- It throws
- INDEX_NONE
Which type should hold text the player reads, such as a button label?
- FName
- FString
- FText
- TCHAR*