为什么不能for_each修改其functor参数? [英] Why can't for_each modify its functor argument?

查看:123
本文介绍了为什么不能for_each修改其functor参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


http://www.cplusplus.com/reference/ algorithm / for_each /

一元函数接受
中的元素作为参数的范围。这可以是
是一个指向一个函数的指针或一个
对象,其类重载
operator()。它的返回值,如果有的话,
被忽略。

http://www.cplusplus.com/reference/algorithm/for_each/
Unary function taking an element in the range as argument. This can either be a pointer to a function or an object whose class overloads operator(). Its return value, if any, is ignored.

根据这篇文章,我期望for_each实际修改对象作为它的第三个参数,但似乎for_each操作临时对象,甚至不修改给它的对象。

According to this article, I expected that for_each actually modifies the object given as its third argument, but it seems like for_each operates on a temporary object, and doesn't even modify the object given to it.

因此,为什么它实现以这种方式?这似乎不太有用。或者我是否误解了某些东西,下面的代码包含错误?

So, why is it implemented in that way? It seems much less useful. Or did I misunderstand something and my code below contains errors?

#include <iostream>
#include <vector>
#include <algorithm>

template <class T> struct Multiplicator{
    T mresult;
  public:
    const T& result() const{return mresult;}
    Multiplicator(T init_result = 1){
      mresult = init_result;
    }
    void operator()(T element){
      mresult *= element;
      std::cout << element << " "; // debug print
    }
};

int main()
{
    std::vector<double> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    Multiplicator<double> multiply;
    std::for_each(vec.begin(),vec.end(),multiply);
    std::cout << "\nResult: " << multiply.result() << std::endl;
    return 0;
}

预期输出:

1 2 3 Result: 6

1 2 3 Result: 1


推荐答案

函数对象取值。 for_each 返回函数对象,因此如果将其更改为:

The function object is taken by value. for_each returns the function object, so if you change it to:

multiply = std::for_each(vec.begin(),vec.end(),multiply);

您会得到预期的输出。

这篇关于为什么不能for_each修改其functor参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆