Domanda

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?

È stato utile?

Soluzione

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top