Felix Dombek Felix Dombek - 3 months ago 17
C++ Question

How to use std::map::operator= with initializer lists

I asked the same question before about

(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

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


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: