相关疑难解决方法(0)

为什么序列操作算法谓词是通过复制传递的?

我想知道为什么仿algorithm函数通过副本传递给函数:

template <typename T> struct summatory
{
    summatory() : result(T()) {}

    void operator()(const T& value)
    { result += value; std::cout << value << "; ";};

    T result;
};

std::array<int, 10> a {{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 }};
summatory<int> sum;

std::cout << "\nThe summation of: ";
std::for_each(a.begin(), a.end(), sum);
std::cout << "is: " << sum.result;
Run Code Online (Sandbox Code Playgroud)

我期待以下输出:

总和:1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 是:143

但是sum.result包含0,这是在ctor中分配的默认值.实现所需行为的唯一方法是捕获以下内容的返回值for_each …

c++ stl-algorithm c++11

16
推荐指数
2
解决办法
585
查看次数

标签 统计

c++ ×1

c++11 ×1

stl-algorithm ×1