如何修复"非聚合无法使用初始值设定项列表初始化" <map>

How to fix "non-aggregates cannot be initialized with initializer list” <map>

本文关键字:列表 lt gt map 初始化 何修复      更新时间:2023-10-16

这在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");
}