I've recently started teaching myself the standard template library. I was curious as to why the GetTotal() method in this class is returning 0?
...
class Count
{
public:
Count() : total(0){}
void operator() (int val){ total += val;}
int GetTotal() { return total;}
private:
int total;
};
void main()
{
set<int> s;
Count c;
for(int i = 0; i < 10; i++) s.insert(i);
for_each(s.begin(), s.end(), c);
cout << c.GetTotal() << endl;
}
for_each
takes the function by-value. That is, it uses a copy of the functor and not the functor itself. Your local c
is left unchanged.
for_each
returns the functor it used, though, so you could do:
Count c;
c = for_each(s.begin(), s.end(), c);
Or more idiomatically:
Count c = for_each(s.begin(), s.end(), Count());
However, there exists such functionality already (no need for your functor):
int total = std::accumulate(s.begin(), s.end(), 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With