Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of a functor on for_each

Tags:

c++

functor

stl

Why does the for_each call on functor doesn't update sum::total at the end?

struct sum
{
    sum():total(0){};
    int total;

    void operator()(int element) 
    { 
       total+=element; 
    }
};

int main()
{
    sum s;

    int arr[] = {0, 1, 2, 3, 4, 5};
    std::for_each(arr, arr+6, s);
    cout << s.total << endl; // prints total = 0;
}
like image 699
user963241 Avatar asked Mar 12 '11 22:03

user963241


People also ask

Why do we need functors?

Functors give you more flexibility, at the cost of usually using slightly more memory, at the cost of being more difficult to use correctly, and at the cost of some efficiency.

What is std :: For_each?

std::for_each is an STL algorithm that takes a collection of elements (in the form of a begin and end iterator) and a function (or function object), and applies the function on each element of the collection. It has been there since C++98.


1 Answers

for_each takes the functor by value - so it is copied. You can e.g. use a functor which is initialized with a pointer to an external int.

struct sum
{
    sum(int * t):total(t){};
    int * total;

    void operator()(int element)
    {
       *total+=element;
    }
};

int main()
{
    int total = 0;
    sum s(&total);

    int arr[] = {0, 1, 2, 3, 4, 5};
    std::for_each(arr, arr+6, s);
    cout << total << endl; // prints total = 15;
}

Or you can use the return value from for_each

struct sum
{
    sum():total(0){};
    int total;

    void operator()(int element) 
    { 
       total+=element; 
    }
};

int main()
{
    sum s;

    int arr[] = {0, 1, 2, 3, 4, 5};
    s = std::for_each(arr, arr+6, s);
    cout << s.total << endl; // prints total = 15;
}
like image 198
Erik Avatar answered Nov 10 '22 06:11

Erik