c++ - 以列表作为值初始化 map

标签 c++ c++11 initialization stdmap initializer-list

我正在尝试初始化一个包含列表的 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/

相关文章:

c++ - 散列 OLE 变体的推荐实现是什么?

c++ - 如何在STL中使用unordered_set?

c++ - 如何使用 initializer_list

c++ - 这是在 C++11 中使用 unique_ptr 和移动语义实现 pimpl 的正确方法吗

c++ - 是否有自动 noexcept 说明符?

c++ - 未初始化的数据行为是否明确规定?

c++ - 马尔可夫随机场是否在 OpenCV 中实现?

c++ - 为什么这里不对引用初始化执行复制初始化?

class - Scala 类/对象初始化中的奇怪行为

c# - 数组语义初始值设定项如何在 C# 中工作?