Sign in
Log inSign up

Case-Sensitive TMap<FString, int32> in Unreal Engine 4 (in C++)

Jakov Pavlek's photo
Jakov Pavlek
·Oct 29, 2021·

1 min read

Use-Case Scenario

Sometimes, you might need a case-sensitive map to be able to differentiate between Fstring keys that only differ in their letter capitalizations.

The Problem

If you use standard out-of-the-box Unreal Engine 4 solution TMap and try it whether in Blueprints or in C++, you might be surprised that it's not case sensitive. So, how to get a case-sensitive TMap?

Solution

Declaration:

CaseSensitiveLookupKeyFuncs.h

#pragma once

/**
* Template class to support FString to TValueType maps with a case sensitive key
*/
template<typename TValueType>
struct FCaseSensitiveLookupKeyFuncs : BaseKeyFuncs<TValueType, FString>
{
    static FORCEINLINE const FString& GetSetKey(const TPair<FString, TValueType>& Element)
    {
        return Element.Key;
    }
    static FORCEINLINE bool Matches(const FString& A, const FString& B)
    {
        return A.Equals(B, ESearchCase::CaseSensitive);
    }
    static FORCEINLINE uint32 GetKeyHash(const FString& Key)
    {
        return FCrc::StrCrc32<TCHAR>(*Key);
    }
};

GraphMetaDataStruct.h

#include "CaseSensitiveLookupKeyFuncs.h"
#include "Containers/Map.h"

TMap<FString, int32, FDefaultSetAllocator, FCaseSensitiveLookupKeyFuncs<int32>> NodeNames; //Case-sensitive TMap has no support in Blueprints :(

Graph.cpp

GraphMetaDataStruct.NodeNames.Reserve(NodeCount);
if (!GraphMetaDataStruct.NodeNames.Contains(NodeName))
{
    GraphMetaDataStruct.NodeNames.Emplace(NodeName, i);
}
GraphMetaDataStruct.NodeNames[NodeName]

Links:

Conversion to std::wstring