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

前端 未结 13 1815
滥情空心
滥情空心 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:27

    IMHO it's more straight forward and more readable to use a for loop with an if inside it. However, if this is annoying for you, you could use a for_each_if like the one below:

    template 
    void for_each_if(Iter first, Iter last, Pred p, Op op) {
      while(first != last) {
        if (p(*first)) op(*first);
        ++first;
      }
    }
    

    Usecase:

    std::vector v {10, 2, 10, 3};
    for_each_if(v.begin(), v.end(), [](int i){ return i > 5; }, [](int &i){ ++i; });
    

    Live Demo

提交回复
热议问题