【发布时间】:2016-02-27 01:30:24
【问题描述】:
这是我从http://www.catonmat.net/blog/on-functors/复制的函子代码。
#include <algorithm>
#include <iostream>
#include <list>
class EvenOddFunctor {
int even_;
int odd_;
public:
EvenOddFunctor() : even_(0), odd_(0) {}
void operator()(int x) {
if (x%2 == 0) even_ += x;
else odd_ += x;
}
int even_sum() const { return even_; }
int odd_sum() const { return odd_; }
};
int main() {
EvenOddFunctor evenodd;
int my_list[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// ??? why assign
evenodd = std::for_each(my_list,
my_list+sizeof(my_list)/sizeof(my_list[0]),
evenodd); // ???
std::cout << "Sum of evens: " << evenodd.even_sum() << "\n";
std::cout << "Sum of odds: " << evenodd.odd_sum() << std::endl;
// output:
// Sum of evens: 30
// Sum of odds: 25
}
为什么我们需要像evenodd = std::for_each(my_list,一样在操作后将值赋回evanodd对象?我以为由于evenodd对象是从std::for_each更新的,所以不需要赋值操作,但是没有这个赋值,结果显示为0。
【问题讨论】: