joh*_*ego 1 c++ dictionary initialization initialization-list
在 python 中,我可以在字典中有一个字典,如下所示:
dict = { 'a': { 1:1, 2:2, 3:3 },
'b': { 1:1, 2:2, 3:3 },
'c': { 1:1, 2:2, 3:3 } }
Run Code Online (Sandbox Code Playgroud)
在 C++ 中,我必须在另一个地图中使用地图:
std::map< std::string, std::map<int, int> > map1
Run Code Online (Sandbox Code Playgroud)
但是如何实现与 python 示例相同的结构?一直找不到这方面的任何例子。
std::map< std::string, std::map<int, int, int> > ??
std::map<std::string, std::map<int, int>, std::map<int, int>, std::map<int, int> > ??
Run Code Online (Sandbox Code Playgroud)
如果您的意思是地图对象的初始化,那么它可能看起来像
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map< std::string, std::map<int, int> > m =
{
{ "a", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
{ "b", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
{ "c", { { 1, 1 }, { 2, 2 }, { 3, 3 } } },
};
for ( const auto &p1 : m )
{
std::cout << p1.first << ": ";
for ( const auto &p2 : p1.second )
{
std::cout << "{ " << p2.first << ", " << p2.second << " } ";
}
std::cout << '\n';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
程序输出是
a: { 1, 1 } { 2, 2 } { 3, 3 }
b: { 1, 1 } { 2, 2 } { 3, 3 }
c: { 1, 1 } { 2, 2 } { 3, 3 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
308 次 |
| 最近记录: |