how to index a numeric value to return a string

Firstly, im sorry… didnt find a better title name to expose my problem.

Recently i got a problem which is struggling me alot to figure out since my knowledge on C++ is pretty basic, so not easy for me

i have this enum

enum CombatType_t
{
    COMBAT_ICEDAMAGE    = 1 << 9, // 512
    COMBAT_HOLYDAMAGE   = 1 << 10, // 1024
    COMBAT_DEATHDAMAGE  = 1 << 11, // 2048
};

Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t

Something as the following:

enum AbsorbType_t
{
    "elementIce" = 512,
    "elementHoly" = 1024,
    "elementDeath" = 2048
}

On Lua, for example i could make an associative table

local t = {
    [512] = "elementIce"; 
}

And then, to index i could simply do t[512] which returns elementIce

But on C++, i don’t even have a remotyle idea on how to make this, it would mean alot to me if you guys could help me to figure out this matter

>Solution :

In C++, the standard way to make an associative table is std::map:

#include<iostream>
#include<map>
#include<string>
...

   std::map<unsigned, std::string> absorbType = {
      {512, "elementIce"},
      {1024, "elementHoly"},
      {2048, "elementDeath"}
   };

   // Access by index
   std::cout << "512->" << absorbType[512] << std::endl;

Leave a Reply