Get rid of nested for loops with std::ranges
Asked Answered
F

1

6

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?

Fantan answered 16/7, 2021 at 7:59 Comment(0)
S
7

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

Septivalent answered 16/7, 2021 at 8:21 Comment(2)
why do we have to join after each transform?Joinville
@Timo: To flatten the view: to have {vectorB1, vectorB2, ..,vectorBN} into {B1_1, B1_2, .., B2_1, .. BN_M}.Septivalent

© 2022 - 2025 — McMap. All rights reserved.