问题描述
以下哪两种方法更好,为什么?
方法1:
code> void fun(int i){
// do stuff
}
...
for_each(a.begin end(),fun);方法2:
class functor {
public:
void operator()(int i);
};
...
for_each(a.begin(),a.end(),functor());
编辑:应该用这种方式制定,在什么情况下是上述方法之一其他?
感谢太多了!
解决方案
因此,函子具有真正的性能优势,这可能是巨大的在紧的循环。此外,functor通常更容易组合,特别是与STL更好玩:
std :: bind
x
不适用于函数指针。
我讨厌它们如何乱码,但是由于所有的优点,函数指针。
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:
class functor { public: void operator()(int i); }; ... for_each(a.begin(), a.end(), functor());
Edit: Should have formulated it this way, in what situation is one of the above method preferable to the other?
Thanks a lot!
解决方案Functors may (and will) be trivially inlined – this isn't done for regular function pointers.
Thus, functors have a real performance benefit which may be huge in tight loops. Furthermore, functors are generally more easily composable and in particuler play nicer with the STL:
std::bind
x
doesn't work on function pointers, for instance.I hate how they clutter the code but given all the advantages, I'd prefer them over function pointers any time.
这篇关于使用STL算法,最好传递一个函数指针或函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!