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

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

问题描述

http://www.cplusplus.com/reference/algorithm/for_each/
取一个元素的一元函数范围作为参数.这既可以是一个指向函数或类重载的对象操作员().它的返回值,如果有的话,被忽略.

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 << "
Result: " << 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 不能修改它的函子参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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