C++11带列表初始化的嵌套Map

pb3skfrl  于 2022-11-27  发布在  其他
关注(0)|答案(4)|浏览(228)

我有一个嵌套的map,比如map<int, map<int, string>>,我想用一个初始化器列表来初始化它。我可以用一个初始化器列表来初始化一个单级map,但是我似乎无法找出嵌套map的正确语法。这可能吗?
我的天

// This example shows how to initialize some maps
// Compile with this command:
//      clang++ -std=c++11 -stdlib=libc++ map_initialization.cpp -o map_initialization

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main(){
    cout << "\nLearning map initialization.\n" << endl;

    map<int, string> level1map = {
        {1, "a"},
        {2, "b"},
        {3, "c"}
    };

    for (auto& key_value : level1map) {
        cout << "key: " << key_value.first << ", value=" << key_value.second << endl;
    }

//  This section doesn't compile
//  map<int, map<int, string>> level2map = {
//      {0,
//          {0, "zero"},
//          {1, "one"},
//          {2, "two"}
//      },

//      {1,
//          {0, "ZERO"},
//          {1, "ONE"},
//          {2, "TWO"}
//      }
//  };

    return 0;
}
nnsrf1az

nnsrf1az1#

只是内部Map内容周围缺少一对大括号:

map<int, map<int, string>> level2map = {
    {0, {
        {0, "zero"},
        {1, "one"},
        {2, "two"}
    }},

    {1, {
        {0, "ZERO"},
        {1, "ONE"},
        {2, "TWO"}
    }}
};

如果你把它写在一行中,也许会更引人注目。一个四件事的清单:

{0, {0, "zero"}, {1, "one"}, {2, "two"}}

与两件事的列表,其中第二件事是三件事的列表:

{0, {{0, "zero"}, {1, "one"}, {2, "two"}}}
qqrboqgw

qqrboqgw2#

map<int, map<int, string>> level2map = {
        { 0,
        { { 0, "zero" },
        { 1, "one" },
        { 2, "two" } }
        },

        { 1,
        { { 0, "ZERO" },
        { 1, "ONE" },
        { 2, "TWO" } }
        }
};
e7arh2l6

e7arh2l63#

第一对的第二个值缺少{}:

map<int, map<int, string>> level2map = {
  {0, {
          {0, "zero"},
          {1, "one"},
          {2, "two"}
      }
  },

  {1, {
          {0, "ZERO"},
          {1, "ONE"},
          {2, "TWO"}
      }
  }
};
ars1skjm

ars1skjm4#

Map初始化Map:

map<int, map<int, string>> level2map= {{0, {{0, "zero"},{1, "one"},{2, "two"}}},
                                       {1, {{0, "ZERO"},{1, "ONE"},{2, "TWO"}}}};

此外,如果您想访问map of map中的所有元素,则可以使用下面的方法。

for (auto const& x : level2map) {
    cout << x.first << ":";      //
    for (auto const& y : x.second) {
        cout << " " << y.first << " "<< y.second; 
    }
    cout << endl;
}

输出:

0: 0 zero 1 one 2 two
1: 0 ZERO 1 ONE 2 TWO

相关问题