7
votes

I understand that from C++11 I can initialise a container using a brace-enclosed initializer list:

std::map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

Is this also possible for containers of containers?

For example, I have tried the following without success:

std::pair<std::map<int, char>, int> a = {{1, 'c'}, 2};

In Visual Studio 2015 I receive the following compile error:

no instance of constructor "std::map<_Kty, _Ty, _Pr, _Alloc>::map [with _Kty=std::map, std::allocator>>, _Ty=int, _Pr=std::less, std::allocator>>>, _Alloc=std::allocator, std::allocator>>, int>>]" matches the argument list argument types are: ({...}, int)

With MinGW32 the compile error was along the lines of

Could not convert {...} from brace-enclosed initializer list to std::pair...

1

1 Answers

9
votes

You are missing brackets for your map (and "c" should be 'c' because "c" is a const char * not a char, thanks to Bastien Durel):

std::pair<std::map<int, char>, int> a = {{{1, 'c'}}, 2};

To use initializer list to initialize a map, you need a "list of pairs", something like {{key1, value1}, {key2, value2}, ...}. If you want to put this in a pair, you need to add another level of brackets, which yield {{{key1, value1}, {key2, value2}, ...}, second}.