函子返回 0

发布于 2024-08-25 07:53:53 字数 421 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

|煩躁 2024-09-01 07:53:53

for_each 按值获取函数。也就是说,它使用函子的副本而不是函子本身。您的本地 c 保持不变。

for_each 返回它使用的函子,所以你可以这样做:

Count c;
c = for_each(s.begin(), s.end(), c);

或者更惯用的是:

Count c = for_each(s.begin(), s.end(), Count());

但是,已经存在这样的功能(不需要你的函子):

int total = std::accumulate(s.begin(), s.end(), 0);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文