函子返回 0
我最近开始自学标准模板库。我很好奇为什么这个类中的 GetTotal() 方法返回 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for_each
按值获取函数。也就是说,它使用函子的副本而不是函子本身。您的本地c
保持不变。for_each
返回它使用的函子,所以你可以这样做:或者更惯用的是:
但是,已经存在这样的功能(不需要你的函子):
for_each
takes the function by-value. That is, it uses a copy of the functor and not the functor itself. Your localc
is left unchanged.for_each
returns the functor it used, though, so you could do:Or more idiomatically:
However, there exists such functionality already (no need for your functor):