std :: accumulate

作用累加求和,对于字符串可以将其连接起来(string类型的加,相当于字符串连接)

头文件

#include <numeric>

原型

accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

参数

  • first,last:
    将迭代器输入到序列中的初始位置和最终位置。使用的范围是[first,last),它包含所有的元件第一和最后一个,包括由指向的元件第一但不被指向的元素最后。

  • init
    累加器的初始值。

  • binary_op
    自定义数据类型, accumulate提供了回调函数(第四个参数),来实现自定义数据的处理。

返回值

累积 init 和范围内所有元素的结果 [first,last)。

用例1

std::accumulate的具体用法_字符串

#include <iostream>     // std::cout
#include <numeric>      // std::accumulate
#include <functional>	// std::minus

int myfunction(int x, int y)
{
	return 2 * x + y;
}


int main() {
	int init = 100;
	int numbers[] = { 10,20,30 };

	std::cout << "使用默认 accumulate: ";
	std::cout << std::accumulate(numbers, numbers + 3, init);
	std::cout << '\n';

	std::cout << "使用自定义 custom function accumulate: ";
	std::cout << std::accumulate(numbers, numbers + 3, init, myfunction);
	std::cout << '\n';

	return 0;
}

用例2:Lambda表达式

#include <iostream>
#include <numeric>
#include <vector>
#include <string>
#include <functional>

int main()
{
	std::vector<int> v{ 5,2,1,1,3,1,4 };
	std::string s = std::accumulate(
		std::next(v.begin()),
		v.end(),
		std::to_string(v[0]),
		[](std::string a, int b) {
		return a + '-' + std::to_string(b);
	});

	// 5-2-1-1-3-1-4
	std::cout << s << std::endl;
	return 0;
}