c++之std::accumulate连续操作如累加累积等

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

using namespace std;

//http://www.cplusplus.com/reference/numeric/accumulate/
// accumulate example

//100 10 20 30=>100+10*2+20*2+30*2=220
int myfunction(int x, int y)
{
	int ret = x + 2 * y;
	return ret;
}
struct myclass {
	//100 10 20 30=>100+10*3+20*3+30*3=280
	int operator()(int x, int y) { 
		int ret = x + 3 * y;
		return ret; 
	}
} myobject;

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

	std::cout << "using default accumulate: ";
	std::cout << std::accumulate(numbers, numbers + 3, init);//初始值为init=100 累加
	std::cout << '\n';

	std::cout << "using functional's minus: ";
	std::cout << std::accumulate(numbers, numbers + 3, init, std::minus<int>());//初始值为init=100 连续减
	std::cout << '\n';

	std::cout << "using custom function: ";
	std::cout << std::accumulate(numbers, numbers + 3, init, myfunction);//初始值为init=100 元素间连续执行myfunction操作
	std::cout << '\n';

	std::cout << "using custom object: ";
	std::cout << std::accumulate(numbers, numbers + 3, init, myobject);//初始值为init=100 元素间连续执行myobject ()操作
	std::cout << '\n';

	return 0;
}

//http://en.cppreference.com/w/cpp/algorithm/accumulate
//c++之std::accumulate连续操作如累加累积等
//template <class InputIterator, class T> T accumulate(InputIterator first, InputIterator last, T init)
//连续操作,默认操作是添加的元素,但不同的操作可以被指定为binary_op。
int main(int argc, char const *argv[])
{
	int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	size_t size = sizeof(arr) / sizeof(arr[0]);

	cout <<"连加="<<std::accumulate(arr, arr + size, 0) << endl;//累积  连加
	cout <<"连乘="<< std::accumulate(arr, arr + size,
		1,// 累加器初始值。
		multiplies<int>()) << endl;//累积  连乘

	vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	std::string s = std::accumulate(std::next(v.begin()), v.end(),
		std::to_string(v[0]), // start with first element 累加器初始值。
		[](std::string a, int b) {
		return a + '-' + std::to_string(b);
	});

	cout << "链接=" << s << endl;

	test_accumulate002();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值