可能重复:
a中元素的总和std::vector
我想总结std :: vector的项目
例如
std::vector<int > MYvec;
/*some push backs*/
int x=sum(MYVec); //it should give sum of all the items in the vector
Run Code Online (Sandbox Code Playgroud)
怎么写sum功能?
我试过这个
int sum(const std::vector<int> &Vec)
{
int result=0;
for (int i=0;i<Vec.size();++i)
result+=Vec[i];
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是我不喜欢我的做法
尝试使用C++标准库中的accumulate.像这样的东西:
#include <vector>
#include <numeric>
// Somewhere in code...
std::vector<int> MYvec;
/*some push backs*/
int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5992 次 |
| 最近记录: |