簡體   English   中英

如何迭代STL映射中的STL映射?

[英]How can I iterate over an STL map inside an STL map?

我有一個STL映射定義如下:

map<string, map<int, string> > info;

我使用以下代碼迭代該映射:

for( map<string, map<int, string> >::iterator ii=info.begin(); ii!=info.end(); ++ii){
    for(map<int, string>::iterator j=ii->second.begin(); j!=ii->second.end();++j){
        cout << (*ii).first << " : " << (*j).first << " : "<< (*j).second << endl;
    }
}

這是迭代的正確方法還是有更好的方法? 上面的代碼適合我,但我正在尋找一個更優雅的解決方案。

這是正確的,它只是缺少一些typedef和可讀性改進:

typedef std::map<int, std::string> inner_map;
typedef std::map<std::string, inner_map> outer_map;

for (outer_map::iterator i = outerMap.begin(), iend = outerMap.end(); i != iend; ++i)
{
    inner_map &innerMap = i->second;
    for (inner_map::iterator j = innerMap.begin(), jend = innerMap.end(); j != jend; ++j)
    {
        /* ... */
    }
}

如果C ++ 11可用,您可以使用range for循環:

for(auto &i: info) {
    for(auto &j: i.second) {
        /* */
    }
}

如果只有C ++ 11 auto可用:

for( auto i=info.begin(); i!=info.end(); ++i) {
   for( auto j=i->second.begin(); j!=i->second.end(); ++j) {
       /* */
   }
}

如果您可以使用BOOST,則有BOOST_FOREACH:

typedef std::map<int, std::string> inner_map;
typedef std::map<std::string, inner_map> outer_map;

outer_map outer;

BOOST_FOREACH(outer_map::value_type &outer_value, outer){
    BOOST_FOREACH(inner_map::value_type &inner_value, outer_value->second){
        /* use outer_value and inner_value as std::pair */
    }
}

如果c ++ 11可用,我們可以使用stl算法for_each和lambda函數來獲得一個優雅的解決方案

typedef map<int, string> INNERMAP;
typedef map<string, INNERMAP> OUTERMAP;

OUTERMAP theMapObject;
// populate the map object

//現在迭代地圖對象

std::for_each(theMapObject.cbegin(), theMapObject.cend(), 
    [](const OUTERMAP::value_type& outerMapElement)
{
    // process the outer map object
    const INNERMAP& innerMapObject = outerMapElement.second;
    std::for_each(innerMapObject.cbegin(), innerMapObject.cend(), 
        [](const INNERMAP::value_type& innermapElemen)
    {
        //process the inner map element
    });
});

雖然通過在地圖中使用地圖來解決您正在解決的問題尚不清楚,但我認為沒有使用這些迭代器可以更好地迭代所有項目。 要提高代碼可讀性,唯一可以做的就是在模板類型上使用typedef。

但是,將map定義為不是更好的主意

multimap <string, MyClass>

其中MyClass被定義為一對整數和一個字符串,以及轉儲內容的toString()方法等?

如果你想遍歷兩個地圖,那么你提出的方式是最好的方式。 現在,如果您想要做某些特定事情,那么使用算法標題中的函數可能會更好。

如果您可以訪問C ++ 11的功能,那么Juraj Blaho的答案中提出的基於范圍的for循環對我來說似乎是最具可讀性的選項。 但是,如果你可以使用C ++ 17 ,那么你可以使用結構化綁定和這些循環來進一步提高可讀性,因為你可以擺脫所有firstsecond成員:

std::map<std::string, std::map<int, std::string>> info;

for (const auto &[k1, v1] : info) {
    for (const auto &[k2, v2] : v1) {
        std::cout << k1 << " : " << k2 << " : " << v2 << std::endl;
    }
}

Coliru代碼

暫無
暫無

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

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