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

微笑、不失礼 提交于 2019-12-10 18:48:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!