如何使用地图矢量

新手上路,请多包涵
    vector <map<string,string>> dictionary;
    map <string, string> word1;
    map <string, string> word2;

    word1.insert(pair<string, string>("UNREAL","Abc"));
    word2.insert(pair<string, string>("PROPS","Efg"));

    dictionary.push_back(word1);
    dictionary.push_back(word2);

    vector<map<string, string>>::iterator it;
    it = dictionary.begin();

    for( it; it != dictionary.end(); it++)
    {
                cout << it << " " << it << endl; //ERROR
    }

我想显示存储在向量中的数据。请建议我如何显示矢量字典的输出?

原文由 Sunil Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 714
2 个回答

为了解决您的问题,您应该这样做:

 for(it = dictionary.begin(); it != dictionary.end(); it++){
    for(auto it1=it->begin();it1!=it->end();++it1){
        cout << it1->first << " " << it->second << endl;
    }
}

但是,我认为设计有问题。 In your case you do not need vector of map s… you need vector of pair s or just a map

对向量:

 std::vector <std::pair<string,string>> dictionary;
dictionary.emplace_back("UNREAL","Abc");
dictionary.emplace_back("PROPS","Efg");
for(auto const& item:dictionary){
    std::cout << item.first << " " << item.second;
}

地图:

  std::map<string,string> dictionary;
 dictionary.insert("UNREAL","Abc");//also :  dictionary["UNREAL"]="Abc";
 dictionary.insert("PROPS","Efg");//also :  dictionary["PROPS"]="Efg";
 for(auto const& item:dictionary){
     std::cout << item.first << " " << item.second;
 }

因为 map 不仅仅是一对东西,它是一组对(有点不准确)。

原文由 Humam Helfawi 发布,翻译遵循 CC BY-SA 3.0 许可协议

// i is each map in your vector
for (auto i : dictionary) {
    // j is each std::pair<string,string> in each map
    for (auto j : i) {
      // these are the two strings in each pair
      j.first; j.second;
  }
}

这个答案需要 c++11,但现在几乎所有东西都支持它。

原文由 xaxxon 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题