Question

I am using a multilevel map

map<string, map<string, map<string, int>>> _myMap;

How to access the integer value using the iterator of outermost map only?

Please help me in finding suitable references for 3-level map too.

Was it helpful?

Solution

You may use the following to retrieve the 'first' inner int (Assuming there exist).

int i = it->second.begin()->second.begin()->second;

To iterate over all values, you may use:

  • C++11:

    for (/*const*/ auto& p1 : _myMap) {
        const std::string& s1 = p1.first;
        for (/*const*/ auto& p2 : p1.second) {
            const std::string& s2 = p2.first;
            for (/*const*/ auto& p3 : p2.second) {
                const std::string& s3 = p3.first;
                /*const*/ int& value = p3.second;
    
                // Do what you want.
            }
        }
    }
    
  • C++03:

    typedef map<string, int> map3;
    typedef map<string, map3> map2;
    typedef map<string, map2> map1;
    
    for (map1::/*const_*/iterator it1 = _myMap.begin(), end1 = _myMap.end(); it1 != end1; ++it1) {
        const std::string& s1 = it1->first;
        for (map2::/*const_*/iterator it2 = it1->second.begin(), end2 = it1->second.end(); it2 != end2; ++it2) {
            const std::string& s2 = it2->first;
            for (map3::/*const_*/iterator it3 = it2->second.begin(), end3 = it2->second.end(); it3 != end3; ++it3) {
                const std::string& s3 = it3->first;
                /*const*/ int& value = it3->second;
    
                // Do what you want.
            }
        }
    }
    

OTHER TIPS

int myInt = (((*it).second)["index"])["index"];

You can also regenerate a new map with the iterator and iterate througth it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top