using STL to find all elements in a vector

前端 未结 7 754
时光取名叫无心
时光取名叫无心 2020-12-31 08:01

I have a collection of elements that I need to operate over, calling member functions on the collection:

std::vector v;
... // vector is popula         


        
7条回答
  •  感情败类
    2020-12-31 08:16

    Boost Lambda makes this easy.

    #include 
    #include 
    #include 
    
    std::for_each( v.begin(), v.end(), 
                   if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] 
                 );
    

    You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant "is divisible by 2":

    std::for_each( v.begin(), v.end(), 
                   if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]
                 );
    


    Update: Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):

    std::for_each( v.begin(), v.end(),
                   [](MyType& mt ) mutable
                   {
                     if( mt % 2 == 0)
                     { 
                       mt.myfunc(); 
                     }
                   } );
    

    At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.

提交回复
热议问题