Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functor returning 0

Tags:

c++

stl

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;
}
like image 406
Jon Avatar asked Mar 19 '10 03:03

Jon


1 Answers

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);
like image 69
GManNickG Avatar answered Sep 19 '22 09:09

GManNickG