首页 > 解决方案 > 地图内的 C++ 多个地图

问题描述

在 python 中,我可以在字典中有一个字典,如下所示:

dict = {  'a': { 1:1, 2:2, 3:3 }, 
          'b': { 1:1, 2:2, 3:3 }, 
          'c': { 1:1, 2:2, 3:3 }   }

在 C++ 中,我必须在另一个地图中使用地图:

std::map< std::string, std::map<int, int> > map1

但是如何实现与 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> > ??

标签: c++dictionaryinitializationinitialization-list

解决方案


如果您的意思是地图对象的初始化,那么它可能看起来像

#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;
}

程序输出为

a: { 1, 1 } { 2, 2 } { 3, 3 } 
b: { 1, 1 } { 2, 2 } { 3, 3 } 
c: { 1, 1 } { 2, 2 } { 3, 3 } 

推荐阅读