无法在C ++中打印地图值的地图

时间:2019-03-01 10:52:42

标签: c++

我已经在下面的代码片段中尝试过打印地图值的地图,但是我无法访问第二个地图值。

#include <iostream>
#include <iterator>
#include <map>
#include <string>
using namespace std;

int main()
{

map< string, std::map<std::string, int> > someStorage;
//First key values
someStorage["key1"]["This Is Layer one"] = 100;
someStorage["Key1"]["This Is Layer Two"] = 120;

//second key, values
someStorage["key2"]["This Is Layer one"] = 110;
someStorage["key2"]["This Is Layer Two"] = 110;
map< string, std::map<std::string, int> > ::iterator itr;
cout << "\nThe map is : \n";
for (itr = someStorage.begin(); itr != someStorage.end(); ++itr) 
{
 cout << '\t' << itr->first;
 //<< '\t' << (itr->second).first << '\n'  <==problematic part
 //<< '\t' << (itr->second).second << '\n';  <==problematic part
 }
 cout << endl;
return 0;
}
  

如何打印/访问这些值以及如何区分“这是图层”   一个”代表“ key1”和“ key2”。因为我看到它越来越   如果我们分配key2值,则覆盖,key1具有相同的值。为什么?

我还期望键值对以下

Key1 => {这是第一层,100}          {这是第二层,120}

Key2 => {这是第一层,110}        {这是第二层,110}

4 个答案:

答案 0 :(得分:4)

除了此处的其他答案之外,您还可以使用structured binding(自c ++ 17起)来简化此操作:

for (auto const& [key, val] : someStorage) { // val = second map
  for (auto const& [k, v] : val) {           // k = first, v = second
    cout << key << ' ' << k << ' ' << v << '\n';
  }
}

答案 1 :(得分:2)

您需要第二个内部循环来遍历嵌套的std::map。像这样:

for (auto itr = someStorage.cbegin(); itr != someStorage.cend(); ++itr) 
{
    cout << itr->first << " => ";

    for (auto innerItr = itr->second.cbegin(); innerItr != itr->second.cend(); ++innerItr) 
    {
       cout << innerItr->first << " : " << innerItr->second << " ";
    }

    cout << "\n";
}

请注意,对于所需的输出,您需要大写按键,使它们分别为“ Key1”和“ Key2”(这是您所输入的错字)。还要注意,由于循环不会修改容器,因此我将begin/end成员函数更改为cbegin/cend

答案 2 :(得分:1)

您还需要遍历内部地图,例如:

for (auto itr1 = someStorage.begin(); itr1 != someStorage.end(); ++itr1) 
{
    cout << '\t' << itr->first << ":\n";
    for (auto itr2 = itr1->second.begin(); itr2 != itr1->second.end(); ++itr2) 
    {
         cout << "\t\t" << itr2->first << '\n';
         cout << "\t\t" << itr2->second << '\n';
    }
}

答案 3 :(得分:0)

感谢您的输出。我的Gcc版本不支持自动迭代

    for (itr1 = someStorage.begin(); itr1 != someStorage.end(); ++itr1)
{
    cout << '\t' << itr1->first << ":\n";
    std::map<std::string, int> ::iterator itr2;
    for (itr2 = itr1->second.begin(); itr2 != itr1->second.end(); ++itr2)
    {
         cout << "\t\t" << itr2->first << '\n';
         cout << "\t\t" << itr2->second << '\n';
    }
}