C++ --STL常用算法

C++ --STL常用算法,第1张

文章目录
  • 累加和填充
  • 一、accumulate
  • 二、fill

累加和填充
  • accumulate
  • fill
    必须包含头文件 numeric
一、accumulate
  • 实现类加的功能
算术生成算法:头文件<numeric>
accumulate, fill
//accumulate:累加
#include 
#include 
void test()
{
	vector<int> v;
	for (int i = 1; i < 100; i++)
	{
		v.push_back(i);
	}
	//计算v中所有元素的和
	int result = accumulate(v.begin(), v.end(), 0);				//0是初始的累加值
	cout << result << endl;
}
int main()
{
	test();
	return 0;
}
二、fill
  • 将指定范围的元素全部填充为指定元素
//fill:填充值
#include 
#include 
#include 
class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test()
{
	vector<int> v;
	v.resize(10);			//resize,默认填充数值0
	fill(v.begin(), v.end(), 100);
	for_each(v.begin(), v.end(), MyPrint());
	cout << endl;
}
int main()
{
	test();
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/713482.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存