C++STL库中常用生成算术算法有 accumulate 和 fill
在调用这些算法之前需要包含头文件 #include <numeric> 这个头文件很小,因为算法比较少
1.accumulate
accumulate(iterator beg, iterator end, value); - 第三个参数value是起始累加值 能指定起始累加起始值。
accumulate的底层十分简单,就是用一个for循环通过迭代器访问区间元素
template<class _InIt,
class _Ty,
class _Fn2> inline
_Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func)
{ // return sum of _Val and all in [_First, _Last), using _Func
for (; _First != _Last; ++_First)
_Val = _Func(_Val, *_First);
return (_Val);
}
如果你没有指定function,没写第四个参数 for循环内部也就是在执行 value += *_First;
这个_Frist是你的起始迭代器,循环结束条件为 _First!=_Last。
下面是使用案例:
统计一组人员的年龄总和
class Person
{
public:
Person(string name, int age)
{
this->m_Age = age;
this->m_Name = name;
}
string m_Name;
int m_Age;
};
class AddPerson
{
public:
int operator()(int val, const Person &p1)
{
return val + p1.m_Age;
}
};
void Test1()
{
vector<Person> v;
Person p1("张三", 20);
Person p2("李四", 25);
Person p3("王五", 23);
Person p4("赵六", 22);
Person p5("yrl", 21);
Person p6("xhc", 20);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
v.push_back(p6);
int total = accumulate(v.begin(), v.end(), 0, AddPerson());
cout << "容器中所有人的年龄总和为:" << total << endl;
}
int main()
{
Test1();
system("pause");
return 0;
}
输出结果:
![](https://img-blog.csdnimg.cn/d90a940980fa4f79a1e7006100013b37.png)
2.fill
fill(iterator beg, iterator end, value); - 第三个参数是你要填充的值
fill的底层也很简单
底层是一个for循环 拿到迭代器 *first = value 然后 迭代器往后走
下面是fill的使用案例:
后期想要重新填充容器中的元素
class Print
{
public:
void operator()(int val)
{
cout << val << " ";
}
};
void Test1()
{
vector<int> v;
v.resize(10); // 10个0
//后期重新填充
fill(v.begin(), v.end(), 100);
for_each(v.begin(), v.end(), Print());
cout << endl;
}
int main()
{
Test1();
system("pause");
return 0;
}
输出结果:![](https://img-blog.csdnimg.cn/f5de5f30e2a64a74919d72467a0eedec.png)