开发者

functor returning 0

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开发者_JAVA技巧;
};

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜