Search code examples
c++c++11stdmapuniform-initialization

C++0x 3d map initializing like in php associative arrays


i'm just getting into new c++0x stuff and instancing a map like this:

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

is easily possible. But can i do something like in php?

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

I'm not familiar with the syntax. Maybe something like this

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

So i dont have to write the index all the time:

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

Solution

  • Yes, using c++11 feature uniform initialization:

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

    Output:

    pair:
      (9, 10)
    
    simple_map:
      (5, 6)
      (7, 8)
    
    complex_map:
      (1, (3, 4)(5, 6))
      (2, (7, 8)(8, 8)(9, 0))
    

    See online demo at http://ideone.com/hCjtjP .