c++ - C++设计策略中的 vector 和

标签 c++ stl vector

<分区>

Possible Duplicate:
sum of elements in 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

如何编写sum函数?

我试过了

 int sum(const std::vector<int> &Vec)
 {
    int result=0;
    for (int i=0;i<Vec.size();++i)
      result+=Vec[i];
    return result;
 }

但是我不喜欢我的做法

最佳答案

尝试使用accumulate来自 C++ 标准库。 像这样:

#include <vector>
#include <numeric>

// Somewhere in code...
std::vector<int> MYvec;
/*some push backs*/

int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );

关于c++ - C++设计策略中的 vector 和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3430040/

相关文章:

c++ - 如何折叠STL vector 的子 vector ?

c++ - 无法将 vector <string> 输出到文件

c++ - Objective-C 稳定的 ABI

c++ - 查找最大容器大小 C++

c++ STL remove-if 算法和删除算法问题。

c++ - 空 vector <...> 没有名为的成员

c++ - 根据对的第二个值查找对 vector 的上限

c++ - 使用 opencv 3.0 beta 校准鱼眼镜头

c++ - 如何计算很多数字的乘积?

c++ - 为什么出现 "no matching overload found"错误,即使我定义了它们