Search code examples
c++nested-loopsc++20std-ranges

Get rid of nested for loops with std::ranges


Let I have a code:

for (auto& a : x.as)
{
    for (auto& b : a.bs)
    {
        for (auto& c : b.cs)
        {
            for (auto& d : c.ds)
            {
                if (d.e == ..)
                {
                    return ...
                }
            }
        }   
    }
}

as, bs, cs, ds - std::vector of corresponding elements.

Is it possible with std::ranges to convert four ugly loops into a beatifull one line expression?


Solution

  • With join and transform views, you might do:

    for (auto& e : x.as | std::views::transform(&A::bs) | std::views::join
                        | std::views::transform(&B::cs) | std::views::join
                        | std::views::transform(&C::ds) | std::views::join
                        | std::views::transform(&D::e))
    {
        // ...
    }
    

    Demo