赞
踩
accumulate定义于头文件 <numeric>,计算给定值初始值与给定范围 [first, last) 中元素的和。
函数原型
template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );
template< class InputIt, class T, class BinaryOperation >
constexpr T accumulate( InputIt first, InputIt last, T init,
BinaryOperation op );
参数
Ret fun(const Type1 &a, const Type2 &b);
注:
op
操作必须不非法化涉及范围的任何迭代器,含尾迭代器,且不修改其所涉及范围的任何元素及 *last 。std::accumulate(rbegin, rend, initval, func)
。可能的实现方式:
template<class InputIt, class T>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init)
{
for (; first != last; ++first) {
init = std::move(init) + *first; // C++20 起有 std::move
}
return init;
}
template<class InputIt, class T, class BinaryOperation>
constexpr // C++20 起
T accumulate(InputIt first, InputIt last, T init,
BinaryOperation op)
{
for (; first != last; ++first) {
init = op(std::move(init), *first); // C++20 起有 std::move
}
return init;
}
测试用例
注意,以下测试用例分别用到了这几种函数:
下面是测试代码:
int main() { std::vector<int> vec(10); std::iota(vec.begin(), vec.end(), 1);// { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = std::accumulate(vec.begin(), vec.end(), 0); // 累加,初值为0 // 计算阶乘 multiplies是二进制函数对象,其调用返回其两个参数乘法的结果 int product = std::accumulate(vec.begin(), vec.end(), 1, std::multiplies<int>()); // 使用匿名函数构建可调用对象,参与到accumulate的op运算中。 // 此可调用对象功能为返回 a,b ,‘- ’的拼接结果 auto dash_fold = [](std::string a, int b) { return std::move(a) + '-' + std::to_string(b); }; std::string s = std::accumulate(std::next(vec.begin()), vec.end(), std::to_string(vec[0]), // 用首元素开始 dash_fold); // 使用逆向迭代器右折叠 std::string rs = std::accumulate(std::next(vec.rbegin()), vec.rend(), std::to_string(vec.back()), // 用首元素开始 dash_fold); std::cout << "sum: " << sum << '\n' << "product: " << product << '\n' << "dash-separated string: " << s << '\n' << "dash-separated string (right-folded): " << rs << '\n'; } /* 输出结果: sum: 55 product: 3628800 dash-separated string: 1-2-3-4-5-6-7-8-9-10 dash-separated string (right-folded): 10-9-8-7-6-5-4-3-2-1 */
补充几种常见的op操作:
// std::minus int numbers[] = { 10,20,30 }; int result = std::accumulate(numbers, numbers + 3, 100, std::minus<int>()); std::cout << "The minus of 100-10-20-30 is " << result << ".\n"; // 40 // std::plus int num[] = { 10,20,30 }; int res = std::accumulate(num, num + 3, 100, std::plus<int>()); std::cout << "The sum of 100+10+20+30 is " << res << ".\n"; // 160 // std::multiplies int nums[] = { 10,20,30 }; int ress = std::accumulate(nums, nums + 3, 100, std::multiplies<int>()); std::cout << "The times of 100*10*20*30 is " << ress << ".\n"; // 600000 // std::divides int array[] = { 1,2,3 }; int ret = std::accumulate(array, array + 3, 101, std::divides<int>()); std::cout << "The Divide of 101/1/2/3 is " << ret << ".\n"; // 16
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。