stl中accumulate可以用于求和,如下:
包含:#include <numeric>
1.函数原型:
accumulate(_InIt _First, _InIt _Last, _Ty _Val)
accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。
2.普通类型:
void main()
{
std::vector < int > v{1, 3, 5, 7, 9};
int nsum = std::accumulate(v.begin(), v.end(), 0);
cout << nsum << endl;
std::vector<string> vs{ "abc", "def", "ghi", "jkl" };
string strRes = std::accumulate(vs.begin(), vs.end(), string(""));
cout << strRes.c_str() << endl;
int a = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());//求积,可以用来计算存储大小,第三个参数表示求积的初值
cout << a << endl;
system("pause");
}
结果:

3.自定义类型:
class person
{
public:
person(string na, int age)
{
name = na;
nage = age;
}
void show()
{
cout << name.c_str() << " " << nage << endl;
}
~person()
{
cout << "~person()\n";
}
int GetAge()
{
return nage;
}
private:
string name;
int nage;
};
void main()
{
std::vector<person> vp{ person("he", 12), person("he", 13), person("he", 14), person("he", 15) };
int nsumx = std::accumulate(vp.begin(), vp.end(),0, [](int a, person p){return a + p.GetAge(); });
cout << nsumx << endl;
system("pause");
}
结果:


这篇博客介绍了STL中的accumulate函数,用于对序列进行求和操作。示例包括对整数向量的求和、字符串连接以及自定义类型(如求年龄总和)。此外,还展示了如何使用自定义操作符实现求积和求自定义属性的总和。
665

被折叠的 条评论
为什么被折叠?



