C++ 中的向量和设计策略
可能的重复:
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
如何编写 sum
函数?
我已经尝试过
int sum(const std::vector<int> &Vec)
{
int result=0;
for (int i=0;i<Vec.size();++i)
result+=Vec[i];
return result;
}
但是我不喜欢我的方法
Possible Duplicate:
sum of elements in astd::vector
I want to sum the items of a std::vector
For example
std::vector<int > MYvec;
/*some push backs*/
int x=sum(MYVec); //it should give sum of all the items in the vector
How to write sum
function?
I have tried this
int sum(const std::vector<int> &Vec)
{
int result=0;
for (int i=0;i<Vec.size();++i)
result+=Vec[i];
return result;
}
However I don't like my approach
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用 C++ 标准库中的 accumulate 。
像这样的事情:
Try to use accumulate from C++ standard library.
Something like this:
您应该使用
std::accumulate
。You should use
std::accumulate
.是否有一个 std::accumulate 函数可以做到这一点?
Isent there a std::accumulate function that does this?
您必须迭代数组中的所有项目并计算总和,没有更简单的方法。我想 for 循环是最简单的
You have to iterate over all the items in the array and compute the sum, there is no easier way. I guess for cycle is the simplest