stl accumulate

stl中accumulate可以用于求和,如下:

包含:#include
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");
}

结果:
在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部