Using STL algorithms, is it better to pass a function pointer or a functor?

前端 未结 6 2173
臣服心动
臣服心动 2021-02-20 05:04

Which of these 2 methods is better and why?

Method 1:

void fun(int i) {
  //do stuff
}

...
for_each(a.begin(), a.end(), fun);

Method 2

6条回答
  •  渐次进展
    2021-02-20 05:25

    One big advantage of a function object over a function pointer is that you can more easily bind up some arguments at function object construction.

    An example of a functor that might do this would be

      class multiplyBy
      {
      private:
          int m_whatToMultiplyBy;
      public:
          multiplyBy(int whatToMultiplyBy) : 
              m_whatToMultiplyBy(whatToMultiplyBy)
          {
          }
    
          void operator()(int& i)
          {
              i = m_whatToMultiplyBy * i;
          }
      }
    
    
      ...
    
      // double the array
      for_each(a.begin(), a.end(), multiplyBy(2));
    

    This "binding" of arguments can be done quite nicely with boost::bind and boost::function if boost is available to you.

提交回复
热议问题