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?
This was just asked here.
The reason is that (as you guessed)
std::for_eachcopies its functor, and calls on it. However, it also returns it, so as outlined in the answer linked to above, use the return value forfor_each.That said, you just need to use
std::accumulate:A functor and
for_eachisn’t correct here.For your usage (counting some, ignoring others), you’ll probably need to supply your own functor and use
count_if:And with C++0x lambda’s for fun (just because):
Much nicer.