Sign in to follow this  
sfx81

std::map initialization

Recommended Posts

sfx81    131
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
SiCrane    11839
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
theOcelot    498
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this