5

I have a look up table in my C++ program and for now I have to initialize it at the beginning of the program using something like this:

static const map<string, int> m;
m["a"] = 1;
m["b"] = 2;
...

I am just wondering if there is anyway I can make this initialization process happen at compile time rather than run time? I understand this has very small impact of performance to my program. I am just curious that with in the scope of current C++11/14/17 semantic it is possible or not.

Bob Fang
  • 6,963
  • 10
  • 39
  • 72

1 Answers1

6

No, you can't initialize the std::map with data in compile time!

However, you can use this "fancier" initializer if you prefer, then you can have your data in a const std::map, in case this is what you are trying to do.

static const map<string, int> m = {
    { "a", 1 },
    { "b", 2 }
};

But AGAIN, this WILL NOT initialize the std::map itself in compile time. Behind the scenes, std::map will do the job in runtime.

Wagner Patriota
  • 5,494
  • 26
  • 49