是否可以对容器的容器使用大括号括起来的初始化列表?
Is it possible to use a brace-enclosed initializer list for a container of a container?
我了解到,从 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 年我收到以下编译错误:
no instance of constructor "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>>]" matches the argument list
argument types are: ({...}, int)
对于 MinGW32,编译错误是
Could not convert {...} from brace-enclosed initializer list to std::pair...
您的地图缺少括号(并且 "c"
应该是 'c'
因为 "c"
是 const char *
而不是 char
,感谢 Bastien杜雷尔):
std::pair<std::map<int, char>, int> a = {{{1, 'c'}}, 2};
要使用初始化列表来初始化地图,您需要 "list of pairs",例如 {{key1, value1}, {key2, value2}, ...}
。如果你想把它放在一对中,你需要添加另一层括号,这会产生 {{{key1, value1}, {key2, value2}, ...}, second}
.
我了解到,从 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 年我收到以下编译错误:
no instance of constructor "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>>]" matches the argument list argument types are: ({...}, int)
对于 MinGW32,编译错误是
Could not convert {...} from brace-enclosed initializer list to std::pair...
您的地图缺少括号(并且 "c"
应该是 'c'
因为 "c"
是 const char *
而不是 char
,感谢 Bastien杜雷尔):
std::pair<std::map<int, char>, int> a = {{{1, 'c'}}, 2};
要使用初始化列表来初始化地图,您需要 "list of pairs",例如 {{key1, value1}, {key2, value2}, ...}
。如果你想把它放在一对中,你需要添加另一层括号,这会产生 {{{key1, value1}, {key2, value2}, ...}, second}
.