4

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++?

2
  • 5
    In C++ the "associative table" is called std::map. Commented Feb 6, 2022 at 9:05
  • 1
    Additionally, if you do not need the keys held in sort-order, then use std::unordered_map. For 3 entries -- it doesn't matter from a performance standpoint, but for 3-million it would. Commented Feb 6, 2022 at 9:30

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

2 Comments

I had the feeling it was pretty easy but had no clue how, thank you so much! Glad to learn something new
It will make no difference here. But maybe we could also consider a std::unordered_map
2

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;
}

2 Comments

using namespace std and prefixing with std:: are somehow redundant ...
@Sebastian. You are right. I'll leave it there for illustration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.