【问题标题】:Why does 'for_each' not reading function object为什么'for_each'不读取函数对象
【发布时间】:2018-12-16 03:11:36
【问题描述】:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template <class T>
class Sum {
public:
    Sum(T i = 0) : res(i) {}
    void operator()(T x) { res =res + x; }
    T result() const { return res; }
private:
    T res;
};

int main() {
    Sum<int> s;
    vector<int> vec;
    vec.insert(vec.begin(), 10);
    vec.insert(vec.begin()+1, 10);
    vec.insert(vec.begin()+2, 10);

    vector<int>::iterator itr = vec.begin();
    cout << *itr << endl;
    for_each(vec.begin(), vec.end(), s);
    cout << "sum is" << s.result() << endl;
    return 0;
}

这是我的代码。我想在 Sum res 类中添加 vec 值。 for_each 应该调用soperator(),所以结果应该是30,但它显示的是0。

我认为在向量中添加值没有问题。为什么s.operator() 不起作用?

【问题讨论】:

标签: c++


【解决方案1】:

for_each 通过值获取其第三个参数,这意味着operator() 的每次调用都会影响s 的一个完全独立的副本。有一种算法可以准确地解决您正在做的事情,称为std::accumulate,但如果您希望它与for_each 一起使用,您需要使用&lt;functional&gt; 中的std::ref“通过引用”传递s

for_each(vec.begin(), vec.end(), ref(s));

【讨论】:

    【解决方案2】:

    for_each 返回传入函子的副本,该函子提供迭代的“结果”(无论结果是什么)。将您的呼叫更改为:

    auto s = for_each(vec.begin(), vec.end(), Sum&lt;int&gt;());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多