问题
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.
回答1:
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:
- Initializing map of maps with initializer list in VS 2013
- Using Initializer Lists with std::map
- Is this a compiler bug? Am I doing something wrong?
来源:https://stackoverflow.com/questions/40638498/how-to-use-stdmapoperator-with-initializer-lists