簡體   English   中英

從常數迭代器到地圖矢量的地圖矢量中獲取地圖元素的鍵和值

[英]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);
}

遍歷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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM