如何在给定第一个索引的情况下打印2D地图中的所有元素

时间:2017-07-25 20:22:56

标签: c++

正如标题所说,我想打印出" group1"的所有元素。在这个2D地图中。我试过这个但是我在for循环中遇到了一个巨大的错误。

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

int main(){
  map<string,map<int,double> > myMap;
  myMap["group1"][13] = 10.41;
  myMap["group1"][15] = 31.2;

  //print all elements in "group1"
  for (map< string, map<int,double> >::const_iterator iter = 
       myMap["group1"].begin(); iter != myMap["group1"].end(); ++iter)
       {
         cout << iter->first << '\t' << iter->second << '\n';
       }

  return 0;
} 

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:1)

你想要一个内部map<int,double>的迭代器,而你想要得到你的外部map<string,map<int,double> >的迭代器:

int main() {
    map<string, map<int, double> > myMap;
    myMap["group1"][13] = 10.41;
    myMap["group1"][15] = 31.2;

    //print all elements in "group1"
    for (map<int, double>::const_iterator iter =
        myMap["group1"].begin(); iter != myMap["group1"].end(); ++iter)
    {
        cout << iter->first << '\t' << iter->second << '\n';
    }

    return 0;
}

答案 1 :(得分:1)

myMap["group1"]的类型为map<int,double>而不是map<string,map<int,double>>

然后你的代码会看起来像这样:

const map<int,double> &grp1map = myMap["group1"];
for (map<int,double>::const_iterator iter = grp1map.begin(); iter != grp1map.end(); ++iter)
{
    cout << iter->first << '\t' << iter->second << '\n';
}

您可以使用auto

简化此操作
auto &grp1map = myMap["group1"];
for (auto iter = grp1map.begin(); iter != grp1map.end(); ++iter) 
{
    cout << iter->first << '\t' << iter->second << '\n';
}

但无论如何你应该这样做:

for (auto &elem : myMap["group1"] )
{
    cout << elem.first << '\t' << elem.second << '\n';
}