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

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

    Boost provides ranges that can be used w/ range-based for. Ranges have the advantage that they don't copy the underlying data structure, they merely provide a 'view' (that is, begin(), end() for the range and operator++(), operator==() for the iterator). This might be of your interest: http://www.boost.org/libs/range/doc/html/range/reference/adaptors/reference/filtered.html

    #include 
    #include 
    #include 
    
    struct is_even
    {
        bool operator()( int x ) const { return x % 2 == 0; }
    };
    
    int main(int argc, const char* argv[])
    {
        using namespace boost::adaptors;
    
        std::vector myCollection{1,2,3,4,5,6,7,8,9};
    
        for( int i: myCollection | filtered( is_even() ) )
        {
            std::cout << i;
        }
    }
    

提交回复
热议问题