std::累积BinaryOperator副作用
std::accumulate BinaryOperator side effects
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);
相关文章:
- 复制构造函数的奇怪副作用
- 程序只适用于包含(无副作用)cout声明
- 为什么评估一个表达可能会产生副作用
- strncmp 有副作用吗?
- 具有必要副作用的静态初始化被优化掉了
- 使用运营商New分配的数据结构是否有任何副作用
- 操作员的排序规则和副作用
- 如果 LTO 中的代码依赖于其构造的副作用,是否允许 LTO 删除未使用的全局对象?
- 默认参数中的 c++ new 运算符及其副作用
- 使用 gcc 的 -fno-math-errno 可能有什么副作用?
- ClangAST Consumer:如何在 FunctionDecl 中遍历语句、VarDecl、BinaryOpera
- 返回对象的攻击子具有副作用
- 初始化类模板的静态成员会产生副作用
- 斯特伦有副作用吗
- 警告表达副作用
- min()函数的副作用
- C++按引用传递和按值函数传递副作用
- 成员子对象继承存储持续时间是否有任何非直观的副作用
- 为什么libcurl需要"CURLOPT_NOSIGNAL"选项,启用后会有什么副作用
- 返回值和副作用编码之间有什么区别