Search code examples
c++11initializer-list

c++11: initialize map with explicit initializer_list object


In C++11 I can initalize a map with an initializer_list like this:

map<string, int> mymap = {{"first", 1}, {"second", 2}};

But not like this:

initializer_list<pair<string,int>> il = {{"first", 1}, {"second", 2}};

map<string, int> mymap2{il};

Any idea why is that? Is there a different syntax for that or is it not possible at all?

Thanks.


Solution

  • The initializer_list constructor of map takes a list of value_type, which is a pair with first element const.

    This will work:

    initializer_list<pair<string const,int>> il = {{"first", 1}, {"second", 2}};
                                ^^^^^^