Home > Software engineering >  How to iterate through a collection of maps of different kinds using range based 'for' loo
How to iterate through a collection of maps of different kinds using range based 'for' loo

Time:12-01

I can iterate through a map as follows:

std::map<int, std::string> intMap = { {1, "one"}, {2, "two"}, {3, "three"} };

for (const auto &[k, v]: intMap)
{
    doSomething(k, v);
}

I have another map (of different type and size) defined as follows:

std::map<float, std::string> floatMap = { {1.0, "one"}, {2.0, "two"}};

I want to do the same thing for this map as well (doSomething(k, v) is templated)

for (const auto &[k, v]: floatMap)
{
    doSomething(k, v);
}

Is there a way where I can do this for both the maps by iterating through the collection of maps?

Something like:

for (const auto &map: {intMap, floatMap})
{
    for (const auto &[k, v]: map)
    {
        doSomething(k, v);
    }
}

This however gives the error:

cannot deduce type of range in range-based 'for' loop

What's the cleanest way (> C 17) to iterate through a collection of maps (of different kinds) using range-based 'for' loops?

Thanks!

CodePudding user response:

You can use fold expression to expand immediately invoked lambda to do this:

[](const auto&... maps) {
  ([&] {
    for (const auto& [k, v] : maps)
      doSomething(k, v);
   }(), ...);
}(intMap, floatMap);

Demo.

  • Related