std::累积BinaryOperator副作用

std::accumulate BinaryOperator side effects

本文关键字:副作用 BinaryOperator 累积 std      更新时间:2023-10-16

std::accumulate documentation on cppreference.com声明:

op不能使任何迭代器无效,包括结束迭代器,或者修改所涉及范围的任何元素(从c++11开始)

稍后,它显示了一个可能的实现,我在这里报告:

template<class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, 
             BinaryOperation op)
{
    for (; first != last; ++first) {
        init = op(init, *first);
    }
    return init;
}

假设std::accumulate的实现,op如何"使一些迭代器无效"或"修改范围的元素"?

您可以定义一个lambda来修改范围中的元素和/或修改范围本身。例如,使用以下lambda将违反std::accumulate的先决条件:

std::vector<int> v{0,1,2,3,4};
auto illegal_op = [&v](int init, int val) { 
    v.back() *= 2;      // modifying elements in the range
    v.push_back(42);    // invalidating iterators in the range
    return init + val;
};
std::accumulate(v.begin(), v.end(), 0, illegal_op);