如何使用地图矢量

Sun*_*ngh 3 c++ dictionary vector

    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
    }
Run Code Online (Sandbox Code Playgroud)

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

xax*_*xon 5

// 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;
  } 
}
Run Code Online (Sandbox Code Playgroud)

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


Hum*_*awi 5

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

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

但是,我认为设计存在问题。在你的情况,你不需要做vectormap小号......你需要vectorpairS或只是一个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;
}
Run Code Online (Sandbox Code Playgroud)

地图:

 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;
 }
Run Code Online (Sandbox Code Playgroud)

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