1

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?

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • http://www.sgi.com/tech/stl/for_each.html has an example like this one but working – Dan D. Apr 30 '11 at 18:51
  • Duplicate of [Why can't for_each modify its functor argument?](http://stackoverflow.com/questions/2102056/why-cant-for-each-modify-its-functor-argument) – James McNellis Apr 30 '11 at 18:54

2 Answers2

4

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);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    @Seth: Here's the first thing I could think of: Because in many cases, you might provide it with a *temporary* functor, e.g. `for_each(..., Object())`. If it took, say, a reference, then this would not be possible, as C++ prohibits binding a non-`const` reference to a temporary. – Oliver Charlesworth Apr 30 '11 at 18:51
  • 1
    @Seth: The answer (a philosophical answer) to your question *"Why does it do that?"* can be found here : [What is wrong with `std::set`?](http://stackoverflow.com/questions/5397616/what-is-wrong-with-stdset) – Nawaz Apr 30 '11 at 18:58
3

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!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • The point wasn't to accumulate a sum of `int`s, the point was to use `for_each`. But thanks and +1, `accumulate` is nice to know about. – Seth Carnegie Apr 30 '11 at 18:58
  • 1
    @Seth: I thought it would be good if you also know the alternatives, but yeah, agree, it doesn't answer your question. @Oli already have explained that. I didn't feel repeating the same. However, you can read this interesting topic to know the philosophical answer to your question : [What is wrong with `std::set`?](http://stackoverflow.com/questions/5397616/what-is-wrong-with-stdset) – Nawaz Apr 30 '11 at 19:01