std::map initialization

Started by
2 comments, last by theOcelot 14 years, 1 month ago
Hi All. I was wondering if there is any other way to initialize static map member. e.g std::map<int,int> A::MyMap; class A { public : A() { static bool mapInit = false; if ( !mapInit ) { mapInit = true; MyMap[0] = 100; MyMap[1] = 200; ... } } static std::map<int,int> MyMap; }; Thanks , Kazz
Advertisement
Yeah, there are other ways. One example:
class A {  public :    static std::map<int,int> MyMap;};std::pair<int, int> initializers[] = {  std::pair<int, int>(0, 100),  std::pair<int, int>(1, 200)};std::map<int,int> A::MyMap(initializers, initializers + sizeof(initializers)/sizeof(initializers[0]));
Another option is Boost.Assignment.
A private lazy global.
//A.hclass A{    static std::map<int, int>& MyMap();    public:    void Foo(){        MyMap()[17] = 42;        //do other foo with MyMap();    }};//A.cppstd::map<int, int>& A::MyMap(){    static std::map<int, int> map;    static bool initialized = false;    //initialize the map, if it hasn't been already    if(!initialized){   //you may also be able to use the map's empty() member to check.        //fill it in        map[0] = 100;        map[1] = 200;    }    return map;}


You may also be able to just make a plain lazy global in A.cpp, so it doesn't even have to be part of the class declaration, depending on how it's used.

This topic is closed to new replies.

Advertisement