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

前端 未结 13 1707
滥情空心
滥情空心 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条回答
  •  面向向阳花
    2021-01-30 04:03

    Instead of creating a new algorithm, as the accepted answer does, you can use an existing one with a function that applies the condition:

    std::for_each(first, last, [](auto&& x){ if (cond(x)) { ... } });
    

    Or if you really want a new algorithm, at least reuse for_each there instead of duplicating the iteration logic:

    template 
      void
      for_each_if(Iter first, Iter last, Pred p, Op op) {
        std::for_each(first, last, [&](auto& x) { if (p(x)) op(x); });
      }
    

提交回复
热议问题