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

前端 未结 6 2176
臣服心动
臣服心动 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:41

    My opinion - #1 is better, because it's simpler.

    Just because something can be an object, doesn't mean it should be one. I'm sure there are cases where the functor makes sense, but in most cases there's probably no need for it.

提交回复
热议问题