我正在尝试初始化一个包含列表的 map
map<string, list<int>> firstNamesMap = {{"name1", new list<int>}};
我收到以下错误:
error: could not convert ‘{{"name1", (operator new(8), (<statement>, ((std::list<int>*)<anonymous>)))}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::basic_string<char>, std::list<int> >’
map<string, list<int>> firstNamesMap = {{"name1", new list<int>}};
^
我最初试图用 list<Data *>
初始化一个更大的 map 而不是 list<int>
,其中“Data”是之前声明的简单类。但是无论哪种方式都会产生相同的错误。
不确定这是否重要,但我在 Cygwin 中使用 g++ 进行编译。
最佳答案
new list<int>
导致 指向 list<int>
的指针(即 list<int> *
)。但是,查看您的 map
的映射类型 :
map<string, list<int>>
^^^^^^^^^
你真正需要的是一个list<int>
, 不是 list<int>*
.
试试 list<int>()
而不是 new list<int>
初始化 map 时:
map<string, list<int>> firstNamesMap = {{"name1", list<int>()}};
关于c++ - 以列表作为值初始化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110747/