According to the first answer to this question, the functor below should be able to retain a value after being passed to foreach
( I couldn't get the struct Accumulator
in the example to compile, so built a class).
class Accumulator
{
public:
Accumulator(): counter(0){}
int counter;
void operator()(const Card & c) { counter += i; }
};
Example usage ( as per the example )
// 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
is implemented as a std::deque<Card>
. No matter how long _cards
gets, acc.counter
is zero after the for_each
completes. As I step through in the debugger I can see counter incrementing, however, so is it something to do with acc
being passed by value?