简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM