C++学习笔记——STL【算法:算术生成算法】

accumulate 累计操作

使用时包含的头文件为 #include <numeric>

函数签名:

template <class InputIterator, class T>   
T accumulate (InputIterator first, InputIterator last, T init);

template <class InputIterator, class T, class BinaryOperation>   
T accumulate (InputIterator first, InputIterator last, T init,BinaryOperation binary_op);

函数功能:

对容器指定区间内的元素进行累计操作(默认为值累加),可以自定义操作类型

参数说明:

  • first 目标容器的初始位置(包含)
  • last 目标容器的结束位置(不包含)
  • init 累加器的初始值
  • binary_op 指定具体的累计操作,可以是函数指针,也可以是函数对象

函数实现:
函数内部实现等价于:

template <class InputIterator, class T>
   T accumulate (InputIterator first, InputIterator last, T init)
{
  while (first!=last) {
    init = init + *first;  
    // or: init=binary_op(init,*first) for the binary_op version
    ++first;
  }
  return init;
}

应用案例:

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

using namespace std;
// 仿函数:自定义乘法
class MyMultiplication {
public:
	// v1 为累计值
	// v2 为元素值
	int operator()(const int& v1,const int& v2) {
		// cout << v1 << " " << v2 << endl;
		return v1 * v2;
	}
};
// v1 为累计值
// v2 为元素值
int double_add(const int& v1, const int& v2) {
	return v1 + 2 * v2;
}

using namespace std;
int main() {
	// 默认累加元素值
	vector<int>v = {1,2,3,4,5,6,7,8,9,10};
	// 累加器初始值为0
	int result= accumulate(v.begin(), v.end(), 0);
	cout << result << endl; // 55

	// 自定义累计操作 累减:使用内置的函数对象 减法 minus
	int result2 = accumulate(v.begin(), v.end(), 100, minus<int>());
	cout << result2 << endl; // 100 -55 = 45

	// 自定义累计操作 累乘:传入自定义的函数对象
	int result3 = accumulate(v.begin(), v.end(), 1, MyMultiplication());
	cout << result3 << endl; // 3628800

	// 自定义累计操作 累加2倍的元素值:传入函数指针
	int result4 = accumulate(v.begin(), v.end(), 0, double_add);
	cout << result4 << endl; // 110

	return 0;
}

fill 容器填充

使用时包含的头文件为 #include <algorithm>

函数签名:

template <class ForwardIterator, class T>  
void fill (ForwardIterator first, ForwardIterator last, const T& val);

函数功能:

将指定值赋值给目标容器指定范围内的所有元素。
需要提前给容器开辟空间。

参数说明:

  • first 目标容器的初始位置(包含)
  • last 目标容器的结束位置(不包含)
  • val 指定的值

函数实现:

template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
  while (first != last) {
    *first = val;
    ++first;
  }
}

应用案例:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

int main() {
	// 将容器中所有元素赋值为 10(需要提前开辟空间)
	vector<int> v(10);
	fill(v.begin(), v.end(), 10);
	for (vector<int>::iterator p = v.begin(); p != v.end(); p++) {
		cout << *p << " ";
	}
	cout << endl; // 10 10 10 10 10 10 10 10 10 10

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值