C++ での多次元マップの実装

多次元 地図 は、値をキーの組み合わせにマップする場合に使用されます。キーには、ユーザー定義のデータ型を含む任意のデータ型を使用できます。多次元マップは入れ子になったマップです。つまり、キーを別のマップにマップし、そのマップ自体がキー値と対応するマップされた値の組み合わせを格納します。

構文:

 // Creating a two-dimensional map: map object; // Creating an N-dimensional map: map>物体;> 

例 1:




// C++14 code to implement two-dimensional map> > #include> using> namespace> std;> > int> main()> {> > > // Two-dimensional key> > map <> int> , map <> int> ,> int> >> メートル;>> > > // For accessing outer map> > map <> int> , map <> int> ,> int> >>::反復子 itr;>> > > // For accessing inner map> > map <> int> ,> int> >::イテレータ ptr;>> > > for> (> int> i = 0; i <2; i++) {> > for> (> int> j = 0; j <2; j++) {> > m[i][j] = i + j;> > }> > }> > > for> (> int> i = 0; i <2; i++) {> > for> (> int> j = 0; j <2; j++) {> > > // Accessing through array subscript> > cout < <> 'First key is '> < < i> > < <> ' And second key is '> < < j> > < <> ' And value is '> < < m[i][j] < < endl;> > }> > }> > > cout < <> ' Now accessing map though iterator '> ;> > > for> (itr = m.begin(); itr != m.end(); itr++) {> > > for> (ptr = itr->秒.begin(); ptr != itr->second.end(); ptr++) {>> > cout < <> 'First key is '> < < ' And second key is ' < < ' And value is ' } } }>

出力:

 First key is 0 And second key is 0 And value is 0 First key is 0 And second key is 1 And value is 1 First key is 1 And second key is 0 And value is 1 First key is 1 And second key is 1 And value is 2 Now accessing map though iterator First key is 0 And second key is 0 And value is 0 First key is 0 And second key is 1 And value is 1 First key is 1 And second key is 0 And value is 1 First key is 1 And second key is 1 And value is 2 

例 2:




// C++14 code to implement two-dimensional map> // and inserting value through insert()> > #include> using> namespace> std;> > int> main()> {> > > // First key type is a string> > mapint, int>> メートル; Mapint、int>>::イテレータ itr; 地図 ::イテレータ ptr; m.insert(make_pair('Noob', マップ ())); m['Noob'].insert(make_pair(0, 5)); m.insert(make_pair('Geek', マップ ())); m['Geek'].insert(make_pair(1, 10)); m.insert(make_pair('Geek', マップ ())); m['Geek'].insert(make_pair(2, 20)); for (itr = m.begin(); itr != m.end(); itr++) { for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) {コート < < 'First key is ' < < ' And second key is ' < < ' And value is ' } } }>

出力:

 First key is Geek And second key is 1 And value is 10 First key is Geek And second key is 2 And value is 20 First key is Noob And second key is 0 And value is 5