【问题标题】:std::accumulate BinaryOperator side effectsstd::accumulate BinaryOperator 副作用
【发布时间】:2016-07-28 18:11:49
【问题描述】:

std::accumulate 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 如何“使某些迭代器无效”或“修改范围内的元素”?

【问题讨论】:

  • [&amp;vec](int a, int b) { vec.clear(); return a + b; }?

标签: c++ c++11


【解决方案1】:

您可以定义一个 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    相关资源
    最近更新 更多