头文件
#include <numeric>
定义,
(1) template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
(2) template< class InputIt, class T, class BinaryOperation >
T accumulate( InputIt first, InputIt last, T init,
BinaryOperation op );
基本使用
一、累加求和
vector<int> vi{ 1, 2, 3 };
std::cout << accumulate(vi.begin(), vi.end(), 0) << std::endl; // 6
最后一个0为初始值。得到的结果是0+1+2+3 = 6
二、自定义二元函数对象(比如lambda表达式等)
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int> vec0{ 1, 2, 3 };
std::cout << accumulate(vec0.begin(), vec0.end(), 0) << std::endl; // 6
//求vec1中字符串的长度之和
vector<string> vec1 = { "abcd", "ef", "ghi" };
size_t totalSize = accumulate(vec1.begin(), vec1.end(), 0,
[](size_t sum, const std::string& str) { return sum + str.size(); });
std::cout << totalSize << std::endl;
getchar();
return 0;
}
运行结果:
6
9
可能的实现
版本一
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;
}
注意点
一些算法只会读取其输入范围内的元素,而从不改变元素。比如find 和 accumulate。
还有注意std::accumulate返回值类型要注意。
在上面的可能实现中:
T accumulate(InputIt first, InputIt last, T init,
BinaryOperation op)
返回类型为T,和init类型是一致的。
本文深入探讨了C++标准库中的accumulate函数,包括其头文件包含、模板定义及使用案例。通过具体代码示例,讲解了如何进行基本的累加求和操作,以及如何利用自定义二元函数对象(如lambda表达式)来实现更复杂的功能,例如求字符串长度总和。同时,提供了可能的函数实现方式,并强调了算法对输入元素的只读特性。
589

被折叠的 条评论
为什么被折叠?



