Can a functor retain values when passed to std::for_each?

c++, functor

Solution

This was just asked here.

The reason is that (as you guessed) `std::for_each` copies its functor, and calls on it. However, it also returns it, so as outlined in the answer linked to above, use the return value for `for_each`.

That said, you just need to use `std::accumulate`:

int counter = std::accumulate(_cards.begin(), _cards.end(), 0);

A functor and `for_each` isn't correct here.

For your usage (counting some, ignoring others), you'll probably need to supply your own functor and use `count_if`:

// unary_function lives in <functional>
struct is_face_up : std::unary_function<const Card&, const bool>
{
    const bool operator()(const card& pC) const
    {
        return pC.isFaceUp(); // obviously I'm guessing
    }
};

int faceUp = std::count_if(_cards.begin(), _cards.end(), is_face_up());
int faceDown = 52 - faceUp;

And with C++0x lambda's for fun (just because):

int faceUp = std::count_if(_cards.begin(), _cards.end(),
                            [](const Card& pC){ return pC.isFaceUp(); });

Much nicer.

Problem

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?

Original source

Related problems