如何修复"非聚合无法使用初始值设定项列表初始化" <map>
How to fix "non-aggregates cannot be initialized with initializer list” <map>
这在VS2018中有效,但在2008年不起作用,我不确定如何解决它。
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> myMap = {
{"Code", "Test"},
{"Code", "Test1"},
{"Code", "Test2"},
};
}
这是错误:Error 2 error C2552: 'myMap' : non-aggregates cannot be initialized with initializer list
>VS2008是一个旧的编译器,不支持C++11。
您可以插入每个元素:
int main() {
std::map<std::string, std::string> myMap;
myMap["Code"] = "Test";
myMap["Code"] = "Test1";
myMap["Code"] = "Test2";
}
或者您可以使用提升:
#include "boost/assign.hpp"
int main() {
std::map<std::string, std::string> myMap = boost::assign::map_list_of
("Code", "Test")
("Code", "Test1")
("Code", "Test2");
}
选项 1:使用支持 C++11 或更高版本的标准的编译器,其中扩展列表初始化格式正确。(即放弃VS2008(
选项 2:使用符合 C++03(或更早版本,如有必要(的方言编写程序。举个例子:
typedef std::map<std::string, std::string> Map;
typedef Map::value_type Pair;
Pair elements[] = {
Pair("Code", "Test"),
Pair("Code", "Test1"),
Pair("Code", "Test2"),
};
const std::size_t length = sizeof(elements)/sizeof(*elements);
Map myMap(elements, elements + length);
要修复它,您必须使其符合 C++03(这是vs2008
支持的(,所以基本上:
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> myMap;
myMap["Code0"] = "Test0";
myMap["Code1"] = "Test1";
myMap["Code2"] = "Test2";
}
Boost.Assign 可以大大简化生活:
#include <boost/assign.hpp>
#include <map>
#include <string>
int main()
{
::std::map< ::std::string, ::std::string > items;
::boost::assign::insert(items)
("Code", "Test")
("Code", "Test1")
("Code", "Test2");
}
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 呼叫运营商<<临时
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改