C++, can I statically initialize a std::map at compile time?

It’s not exactly static initialization, but still, give it a try.
If your compiler doesn’t support C++0x, I’d go for std::map’s iteration constructor:

std::pair<int, std::string> map_data[] = {
    std::make_pair(1, "a"),
    std::make_pair(2, "b"),
    std::make_pair(3, "c")
};

std::map<int, std::string> my_map(map_data,
    map_data + sizeof map_data / sizeof map_data[0]);

This is pretty readable, doesn’t require any extra libraries and should work in all compilers.

Leave a Comment