首页 文章

是否可以为容器的容器使用括号括起的初始化列表?

提问于
浏览
6

据我所知,从C 11我可以使用大括号括起来的初始化列表初始化一个容器:

std::map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

容器容器也可以吗?

例如,我尝试了以下但没有成功:

std::pair<std::map<int, char>, int> a = {{1, 'c'}, 2};

在Visual Studio 2015中,我收到以下编译错误:

没有构造函数的实例“std :: map <_Kty,_Ty,_Pr,_Alloc> :: map [with Kty = std :: map,std :: allocator >>, Ty = int,Pr = std :: less,std :: allocator >>>, Alloc = std :: allocator,std :: allocator >>,int >>]“匹配参数列表参数类型为:(,int)

使用MinGW32时,编译错误就是这样的

无法将从大括号括起来的初始化列表转换为std :: pair ...

1 回答

  • 8

    您缺少 Map 的括号( "c" 应为 'c' ,因为 "c"const char * 而不是 char ,感谢Bastien Durel):

    std::pair<std::map<int, char>, int> a = {{{1, 'c'}}, 2};
    

    要使用初始化列表初始化 Map ,您需要"list of pairs",类似于 {{key1, value1}, {key2, value2}, ...} . 如果你想把它放在一对中,你需要添加另一个级别的括号,这会产生 {{{key1, value1}, {key2, value2}, ...}, second} .

相关问题