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?
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);