根据这个问题的第一个答案,下面的仿函数在被传递给之后应该能够保留一个值foreach(我无法struct Accumulator在示例中编译,所以构建了一个类)。
class Accumulator
{
public:
Accumulator(): counter(0){}
int counter;
void operator()(const Card & c) { counter += i; }
};
示例用法(根据示例)
// Using a functor
Accumulator acc;
std::for_each(_cards.begin(), _cards.end(), acc);
// according to the example - acc.counter contains the sum of all
// elements of the deque
std::cout << acc.counter << std::endl;
_cards被实现为std::deque<Card>. 不管_cards得到多长时间,完成acc.counter后为零for_each。但是,当我在调试器中逐步执行时,我可以看到计数器在递增,那么这与acc按值传递有关吗?