mannerofallthings mannerofallthings - 3 months ago 17
C++ Question

Iterating through a two dimensional std::unordered_map

I have defined a 2d map as follows:

unordered_map< string, unordered_map<string, Road*>* > matrix;


Where road is simply:

class Road {
public:
Road() : connected(0), weight(0) {}

bool connected;
int weight;
};


I've tried iterating through the map this way, but it failed to compile.

for (auto &i : matrix) {
for (unordered_map< string, unordered_map<string, Road*>* >::iterator iter1 = i.second->begin();
iter1 != i.second->end(); iter1++) {

}
}


Since I know my matrix is always NxN, one thing I can do is

for (auto &i : matrix) {
for (auto &j : matrix) {

}
}


But i was wondering if there is a cleaner approach with varying size.

Answer

Iterating over maps and unordered maps yields key/value pairs. When you do

for (const auto& p : matrix)
    ...

the variable p has type const std::pair<std::string, std::unordered_map<std::string, Road*>*>&. Therefore, to iterate over the inner map, do:

for (const auto& p : matrix)
    for (const auto& q : *p.second) {
        Road *r = q.second;
        ...
    }

You can use p.first to get the outer key, and q.first to get the inner key.

Comments