• Advertisement
Sign in to follow this  

std::map initialization

This topic is 2896 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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]));

Share this post


Link to post
Share on other sites
A private lazy global.
//A.h
class A{
static std::map<int, int>& MyMap();
public:
void Foo(){
MyMap()[17] = 42;
//do other foo with MyMap();
}
};

//A.cpp
std::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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement