Hello, I’m trying to make a TMap of a enum as a key and a array of enum as value.
From what I understand I need to make a Struct of the array enum to use it as a value.
It might be a worthwhile pursuit, to more clearly formulate what you want to achieve with this structure. This might help you chose your setup. IMHO there are a couple of architectural options available for you here. One of them would be using a list of mappings, instead of a map of arrays. Here’s an example:
The data structure would look something like:
UENUM(BlueprintType)
enum class EFruitType : uint8
{
NoFruit = 0,
Apple,
Avocado,
Pitaya,
Banana,
Carambola
};
// Maps a base fruit to a list of fruits.
USTRUCT(BlueprintType)
struct BAKERY_API FFruitMapping
{
GENERATED_BODY()
// The base fruit for your meal.
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Fruits")
EFruitType BaseFruit;
// A list of fruits that go well with the base fruit.
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Fruits")
TArray<EFruitType> GoesWellTogetherWith;
};
USTRUCT(BlueprintType)
struct BAKERY_API FFruitKitchen
{
GENERATED_BODY()
// Name of chef in the fruit kitchen.
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Fruits")
FString ChefName;
// A list of fruit recipes.
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Fruits")
TArray<FFruitMapping> FruitRecipes;
};
And you’d use it like:
// Add a new mapping.
FFruitKitchen AddRecipe(FFruitKitchen Kitchen, FFruitMapping Mapping)
{
Kitchen.FruitRecipes.Add(Mapping);
return Kitchen;
}
// Find a matching list of fruits.
TArray<EFruitType> GoesWellWith(EFruitType BaseFruit, const FFruitKitchen& Kitchen)
{
TArray<EFruitType> Matches;
for (FFruitMapping Mapping : Kitchen.FruitRecipes)
{
if (Mapping.BaseFruit == BaseFruit)
{
for (EFruitType FruitType : Mapping.GoesWellTogetherWith)
{
Matches.Add(FruitType);
}
}
}
return Matches;
}
(The complete example can be viewed at this gist.)
Like any solutions, this has a couple of benefits and drawbacks. One obvious drawback would be, that you can easily add multiple ‘keys’ of the same sort. This can on the other hand be an advantage over the usage of a map, since it would not allow multiple keys of the same type. It’s all depending on what you want to achieve
It is also possible to setup a struct to be used as a key in a TMap, although this gets a bit more involved. If you’d like to read about this option, I would recommend the blog post I wrote about doing so. Hope that helps.