【问题标题】:C++0x 3d map initializing like in php associative arraysC ++ 0x 3d地图初始化就像在php关联数组中一样
【发布时间】:2013-05-22 20:34:34
【问题描述】:

我刚刚开始接触新的 c++0x 内容并像这样实例化地图:

std::map<int, std::map<int, int>> foo;
foo[1][2] = 3;

很容易实现。但是我可以在 php 中做类似的事情吗?

$array = array(
    1 => array(
        2 => array(
            3
        )
    )
);

我不熟悉语法。也许是这样的

foo[][][] = {
    1 {
        2 {3}
    }
};

所以我不必一直写索引:

foo[1][2] = 3;
foo[1][3] = 4;
foo[1][4] = 5;

【问题讨论】:

    标签: c++ c++11 stdmap uniform-initialization


    【解决方案1】:

    是的,使用 c++11 特性统一初始化:

    #include <iostream>
    #include <map>
    
    int main()
    {
        // The value_type of a map is pair<const Key, T>.
        // To initialize a map an initializer list
        // of pair<Key, T> objects must be specified.
    
        // To initialize a pair:
        //
        std::pair<int, int> p{9, 10};
        std::cout << "pair:\n  (" << p.first << ", " << p.second << ")\n\n";
    
        // To initialize a simple map (no nesting)
        // with value_type of pair<int, int>:
        //
        std::map<int, int> simple_map
        {  // K  V
            { 5, 6 },
            { 7, 8 }
        };
        std::cout << "simple_map:\n";
        for (auto const& i: simple_map)
        {
            std::cout << "  (" << i.first << ", " << i.second << ")\n";
        }
        std::cout << "\n";
    
        // To initialize a complex map (with nesting)
        // with value_type of pair<const int, map<int, int>>
        //
        const std::map<int, std::map<int, int>> complex_map
        {  // K       V
           //       k  v
            { 1, { {3, 4},
                   {5, 6} }
            },
            { 2, { {7, 8},
                   {8, 8},
                   {9, 0} }
            }
        };
    
        std::cout << "complex_map:\n";
        for (auto const& mi: complex_map)
        {
            std::cout << "  (" << mi.first << ", ";
            for (auto const& p: mi.second)
            {
                std::cout << '(' << p.first << ", " << p.second << ')';
            }
            std::cout << ")\n";
        }
    }
    

    输出:

    一对: (9, 10) 简单地图: (5, 6) (7, 8) 复杂地图: (1, (3, 4)(5, 6)) (2, (7, 8)(8, 8)(9, 0))

    http://ideone.com/hCjtjP 上查看在线演示。

    【讨论】:

    • 谢谢hmjd。不幸的是,我不能让你们俩都接受,所以我要给第一张海报接受的答案。对不起那个男人!但无论如何,真的很感谢你的时间!
    • 我看到你用一些很酷的例子更新了你的帖子。谢谢大佬!
    【解决方案2】:

    您可以使用统一初始化,但它只适用于初始化,而不适用于其他地方。

    std::map<int, std::map<int, int>> foo = {
        {1, {{2, 3}}}
    };
    

    注意 {2, 3} 周围的额外 {}。要初始化地图,您需要一个initialization_list 对。然后也使用统一初始化构造对。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2011-01-11
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多