Preface

In the development scenario, when you encounter the use of TMap, change the key value type to the custom data type in the project. If no additional coding is done, errors will occur during compilation. Unreal Engine has additional requirements for the data type that you want to use as a TMap key value. It must meet the implementation of hash sequences and conventional comparison operator overloading. The following code simply shows you how to customize the TMap key value type.

Operation

1. Declare the structure type (in the header file), and pay attention to implementing the comparison overloading operation (this is required).

c++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//Declared in the header file
struct FMapKey
{
public:
int32 KeyID;

bool operator ==(const FMapKey& Other) const
{
return KeyID == Other.KeyID;
}
};

The KeyID is used for testing, mainly to compare whether two MapKeys are the same (a data basis for comparison rules)

2. Build a global Hash function to convert FMapKey to Hash

c++
1
2
3
4
5
//Declared in the global domain, I declared it defined in the header file
inline uint32 GetTypeHash(const FMapKey& Explain)
{
return Explain.KeyID;//No actual Hash operation is performed, just use KeyID as a Hash value
}

The main purpose of this function is to convert key values ​​to Hash values. The algorithm is provided and maintained by the designer, and the engine only needs a uint32 value. The hash algorithm should ensure that different key values ​​have different results, and the same key value has the same result.

Conclusion

The types that can be used as TMap key values ​​are: basic data types, pointers, and individual custom types of Unreal. Therefore, it is very necessary to expand the key value type and add your own type as the key value type.

Engine version: 4.27.2