#include<numeric>//算术生成算法头文件
要加的头文件#include<numeric>
accumulate
是 C++ 标准库中的一个算法函数,用于计算给定范围内的数值之和,它位于 <numeric>
头文件中。它的函数原型如下:
template <class InputIt, class T> T accumulate(InputIt first, InputIt last, T init);
其中,InputIt
是一个迭代器类型,表示输入范围的起始和结束位置;T
是要累加的数值类型;init
是初始值,即累加的初始结果。
accumulate
函数会将输入范围 [first, last)
中的元素依次累加到初始值上,并返回最终的累加结果。累加过程中,会使用元素的加法运算符进行累加。
void test01()
{vector<int>v = { 10,20,30 };int n=accumulate(v.begin(), v.end(), 0);//总和上再加0cout << n << endl;
}
//操作对象
class maker
{
public:maker(int age){this->age = age;}
public:int age;
};
struct myfunc
{int operator()(int val, maker& m){return val + m.age;}
};
void test02()
{vector<maker>v = { maker(10),maker(20),maker(30) };int a=accumulate(v.begin(), v.end(), 0, myfunc());cout << a << endl;
}
fill
是 C++ 标准库中的一个算法函数,用于将给定值赋给指定范围内的所有元素。它位于 <algorithm>
头文件中。fill
的函数原型如下:
template <class ForwardIt, class T> void fill(ForwardIt first, ForwardIt last, const T& value);
其中,ForwardIt
是一个前向迭代器类型,表示要填充的范围的起始和结束位置;T
是要赋给元素的值类型;value
是要填充的值。
fill
函数会将输入范围 [first, last)
中的所有元素都赋值为 value
。
void test03()
{vector<int>v;v.resize(10);fill(v.begin(), v.end(), 100);for_each(v.begin(), v.end(), [](int val)->void {cout << val << " "; });
}