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

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

    Also, if you don't care reordering the collection, std::partition is cheap.

    #include 
    #include 
    #include 
    #include 
    
    void DoStuff(int i)
    {
        std::cout << i << '\n';
    }
    
    int main()
    {
        using namespace std::placeholders;
    
        std::vector v {1, 2, 5, 0, 9, 5, 5};
        const int SOMETHING = 5;
    
        std::for_each(v.begin(),
                      std::partition(v.begin(), v.end(),
                                     std::bind(std::equal_to {}, _1, SOMETHING)), // some condition
                      DoStuff); // action
    }
    

提交回复
热议问题