3

I asked the same question before about boost::assign::map_list_of (which didn't get answered), then I thought maybe using brace initialization would help, but it didn't.

This works perfectly:

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

But this doesn't:

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

Visual Studio 2013 gives the error error C2593: 'operator =' is ambiguous, could be either operator=(std::initalizer_list) or operator=(std::map&&).

Is it possible to get the second version to work? For cases where m is a member variable, for example.

Community
  • 1
  • 1
Felix Dombek
  • 12,597
  • 15
  • 71
  • 123

1 Answers1

3

You could construct a temporary and use it in the assignment.

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

If you don't want to repeat the type, you can use decltype.

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

Related SO posts:

Community
  • 1
  • 1
R Sahu
  • 200,579
  • 13
  • 144
  • 260