STL——常用算术生成算法

2023-12-31 06:24:27

注:算术生成算法属于小型算法,使用时包含头文件#include<numeric>

算法简介:

  • accumulate—— // 计算容器元素累计总和
  • fill—— // 向容器中添加元素

1.accumulate

函数原型:

  • accumulate(iterator beg, iterator end, value);——// 计算容器元素累计总和;?beg 开始迭代器;end 结束迭代器;value 起始值
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
//accumulate——算术生成算法
void test()
{
	vector<int>v;
	for (int i = 0; i < 100; i++)
	{
		v.push_back(i);
	}
	//参数3——起始累加值
	int total = accumulate(v.begin(), v.end(), 0);
	cout << "total = " << total << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

2.fill

函数原型:

  • fill(iterator beg, iterator end, value);——// 向容器中填充元素;beg 开始迭代器;?end 结束迭代器;?value 填充的值
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include<algorithm>
//fill——算术生成算法
void Print(int val)
{
	cout << val << " ";
}
void test()
{
	vector<int>v;
	v.resize(10);
	//后期重新填充
	fill(v.begin(), v.end(), 100);
	for_each(v.begin(), v.end(), Print);
	cout << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

注:利用fill可以将容器区间内元素填充为指定的值。

文章来源:https://blog.csdn.net/weixin_64238628/article/details/135306460
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。