Felix Dombek Felix Dombek - 17 days ago 5
C++ Question

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

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.

Answer

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:

Comments