Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to index a numeric value to return a string

Tags:

c++

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
}

In 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"

How can I do this in C++?

like image 263
dohdle Avatar asked Oct 18 '25 17:10

dohdle


2 Answers

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;
like image 180
nielsen Avatar answered Oct 20 '25 07:10

nielsen


You can use a map which is the C++ implementation of a dictionary.

#include <iostream>
#include <map>
using namespace std;

int main()
{
    std::map<int, std::string> m { {512,  "elementIce" }, {1024,  "elementHoly"}, {2048, "elementDeath"}, };

    std::cout<< m[512] << std::endl;
    std::cout<< m[1024] << std::endl;
    std::cout<< m[2048] << std::endl;
    return 0;
}
like image 37
Phillip Ngan Avatar answered Oct 20 '25 09:10

Phillip Ngan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!