Question

I don't use the STL much and I'm wanting to start learning it, so I made a really simple program using the STL's for_each function. Here is the entire program (minus header files):

class Object {
public:
    int s;

    Object() : s(0) { }

    Object(const Object& rhs) : s(rhs.s) { }

    void operator() (int a) {
        s += a;
    }
};

int main () {
    Object sum;
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    for_each(arr, arr + sizeof(arr) / sizeof(int), sum);

    cout << sum.s;

    cin.get();

    return 0;
}

The program outputs 0. I'm definitely using for_each wrongly, but what exactly is wrong with this code?

Was it helpful?

Solution

for_each works with a copy of the functor that you provide, and then returns a copy at the end. You need this:

sum = for_each(arr, arr + sizeof(arr) / sizeof(int), sum);

OTHER TIPS

If you just want to calculate the sum, then you can also use std::accumulate as:

#include <numeric>

int sum =std::accumulate(arr, arr + sizeof(arr) / sizeof(int),0);

No need of functor!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top