[英]Get the key and values of map elements in a vector of maps from a constant iterator to the vector of maps
I have a vector of maps containing strings .,ie, 我有一个包含字符串的地图矢量。
vector< map <string,string> > vectorOfMaps;
vector< map <string,string> >::const_iterator itr =vectorOfMaps.begin();
vectorOfMaps is filled in another function and the caller function can access only the const_iterator itr. vectorOfMaps填充在另一个函数中,并且调用者函数只能访问const_iterator itr。
How do i access the key and its respective value of each map element in the vectorOfMaps? 如何访问vectorOfMaps中每个地图元素的键及其相应值?
Any help appreciated:) 任何帮助表示赞赏:)
EDIT: Got my solution. 编辑:得到了我的解决方案。
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);
}
You can use the first
and second
keywords to access the map
elements as you're iterating over the vector
of map
s. 遍历
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;
}
}
Your solution is bad because you make multiple copies of maps, first one just before the loop and then inside the loop. 您的解决方案很糟糕,因为您要制作多个地图副本,第一个副本位于循环之前,然后在循环内部。 Consider this shorter and faster version:
考虑以下更短,更快的版本:
for (auto const& el: *itrVectorOfMaps)
cout << "Key=" << el.first << " => Value=" << el.second << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.