c++ - 如何将 std::map::operator= 与初始化列表一起使用

标签 c++ c++11 visual-studio-2013 assignment-operator uniform-initialization

我问了同样的问题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/

相关文章:

C++ std::vector<T*> 如果你持有一个指向指针元素的指针,它会在调整大小时变得无效吗?

c# - 使用 IIS 设置在 vs2013 中加载项目失败

c++ - 大括号中发生了什么

c++ - 访问基于linux的iphdr和tcphdr

c++ - 检查参数包是否包含类型

c++ - 存储函数调用和稍后调用的参数列表

c++ - std::tr1::function 和 std::tr1::bind

c# GridViewColumns 缺少程序集引用

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 通过迭代器修改 std::set 元素:为什么我的代码没有编译?