从常量迭代器到映射向量,获取映射向量中映射元素的键和值

Get the key and values of map elements in a vector of maps from a constant iterator to the vector of maps

本文关键字:映射 向量 元素 键和值 获取 常量 迭代器      更新时间:2023-10-16

我有一个包含字符串的映射向量。,即

vector< map <string,string> > vectorOfMaps;
vector< map <string,string> >::const_iterator itr =vectorOfMaps.begin();

vectorOfMaps填充在另一个函数中,调用方函数只能访问const_iterator itr。

如何访问vectorOfMaps中每个map元素的键及其各自的值?

感谢任何帮助:)

编辑:找到我的解决方案了。

map<string,string> myMap = (*itrVectorOfMaps);
while(loop till the end element)
{
    for(map<string,string>::iterator itM = myMap.begin();   
                                    itM != myMap.end(); itM++)
    {
        cout<<"Key="<<itM->first<<" => Value="<<itM->second<<endl;
    }
    itrVectorOfMaps++;
    myMap=(*itrVectorOfMaps);
}

mapvector上迭代时,可以使用firstsecond关键字来访问map元素。

for(auto const& currentMap : vectorOfMaps)  // Loop over all the maps
{
    for(auto const& element : currentMap)   // Loop over elements of current map
    {
        std::string const& key = element.first;
        std::string const& value = element.second;
    }
}

您的解决方案很糟糕,因为您制作了多个映射副本,第一个在循环之前,然后在循环内部。考虑一下这个更短更快的版本:

for (auto const& el: *itrVectorOfMaps)
    cout << "Key=" << el.first << " => Value=" << el.second << endl;