문제

I have a function which makes use of an unordered_map and its only this function in my class which uses it:

void my_func(){
    static std::unordered_map<int,int> my_map;

    //I only want this to be done the first time the function is called.
    my_map[1] = 1;
    my_map[2] = 3;
    //etc

}

How can I insert the elements in to my static unordered_map so that they only get inserted the first time my function is called (just like the memory allocation is only made the first time)?

Is it possible?

도움이 되었습니까?

해결책

In C++11 (which you're presumably using, otherwise there wouldn't be an unordered_map), containers can be populated by a list initialiser:

static std::unordered_map<int,int> my_map {
    {1, 1},
    {2, 3},
    //etc
};

Historically, the cleanest way would be to call a function that returns a populated container:

static std::unordered_map<int,int> my_map = make_map();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top