我问了同样的问题before关于 boost::assign::map_list_of
(没有得到回答),然后我想也许使用大括号初始化会有帮助,但它没有。
这非常有效:
std::map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
但这不是:
std::map<int, char> m;
m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
Visual Studio 2013 给出错误 error C2593: 'operator =' is ambiguous
,可能是 operator=(std::initalizer_list)
或 operator= (std::map&&)
.
是否可以让第二个版本工作?例如,对于 m
是成员变量的情况。
最佳答案
您可以构造一个临时文件并在作业中使用它。
std::map<int, char> m;
m = std::map<int, char>{{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
如果不想重复类型,可以使用decltype
。
std::map<int, char> m;
m = decltype(m){{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
相关的 SO 帖子:
关于c++ - 如何将 std::map::operator= 与初始化列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638498/