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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With