[英]Get the key and values of map elements in a vector of maps from a constant iterator to the vector of maps
我有一个包含字符串的地图矢量。
vector< map <string,string> > vectorOfMaps;
vector< map <string,string> >::const_iterator itr =vectorOfMaps.begin();
vectorOfMaps填充在另一个函数中,并且调用者函数只能访问const_iterator itr。
如何访问vectorOfMaps中每个地图元素的键及其相应值?
任何帮助表示赞赏:)
编辑:得到了我的解决方案。
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);
}
遍历map
的vector
,可以使用first
和second
关键字访问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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.