How can I avoid “for” loops with an “if” condition inside them with C++?

前端 未结 13 1693
滥情空心
滥情空心 2021-01-30 03:31

With almost all code I write, I am often dealing with set reduction problems on collections that ultimately end up with naive \"if\" conditions inside of them. Here\'s a simple

13条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 04:07

    One can describe your code pattern as applying some function to a subset of a range, or in other words: applying it to the result of applying a filter to the whole range.

    This is achievable in the most straightforward manner with Eric Neibler's ranges-v3 library; although it's a bit of an eyesore, because you want to work with indices:

    using namespace ranges;
    auto mycollection_has_something = 
        [&](std::size_t i) { return myCollection[i] == SOMETHING };
    auto filtered_view = 
        views::iota(std::size_t{0}, myCollection.size()) | 
        views::filter(mycollection_has_something);
    for (auto i : filtered_view) { DoStuff(); }
    

    But if you're willing to forego indices, you'd get:

    auto is_something = [&SOMETHING](const decltype(SOMETHING)& x) { return x == SOMETHING };
    auto filtered_collection = myCollection | views::filter(is_something);
    for (const auto& x : filtered_collection) { DoStuff(); }
    

    which is nicer IMHO.

    PS - The ranges library is mostly going into the C++ standard in C++20.

提交回复
热议问题