找出std::vector中所有元素的和的好方法是什么?

假设我有一个向量std::vector<int> vector,其中有几个元素。现在我要求所有元素的和。同样的东西有什么不同的表达方式?


当前回答

Std::accumulate可能有溢出问题,所以最好的方法是对较大的数据类型变量进行基于范围的积累,以避免溢出问题。

long long sum = 0;
for (const auto &n : vector)
  sum += n;

然后使用static_cast<>进一步向下转换为适当的数据类型。

其他回答

这很简单。c++ 11提供了一种简单的方法来对一个向量的元素求和。

sum = 0; 
vector<int> vec = {1,2,3,4,5,....}
for(auto i:vec) 
   sum+=i;
cout<<" The sum is :: "<<sum<<endl; 

最简单的方法是使用std:accumulate of a vector<int> a:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

实际上有相当多的方法。

int sum_of_elems = 0;

c++ 03

Classic for loop: for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it; Using a standard algorithm: #include <numeric> sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0); Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.

c++ 11及以上版本

b.即使将来发生变化,也会自动跟踪vector类型: # include <数字> Sum_of_elems = std::accumulate(vector.begin(), vector.end(), decltype(向量)::value_type (0)); 利用std:: for_each: std:: for_each (vector.begin (), vector.end (), [&] (int n) { Sum_of_elems += n; }); 使用基于范围的for循环(感谢Roger Pate): For (auto& n: vector) Sum_of_elems += n;

c++ 17及以上版本

使用std::reduce,它也照顾到结果类型,例如,如果你有std::vector<int>,你得到int作为结果。如果你有std::vector<float>,你得到float。或者如果你有std::vector<std::string>,你得到std::string(所有字符串连接)。很有趣,不是吗? 自动结果= std::reduce(v.begin(), v.end()); 这个函数还有其他重载,你甚至可以并行运行,如果你有一个大的集合,你想快速得到结果。

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);
 #include<iostream>
    #include<vector>
    #include<numeric>
    using namespace std;
    int main() {
       vector<int> v = {2,7,6,10};
       cout<<"Sum of all the elements are:"<<endl;
       cout<<accumulate(v.begin(),v.end(),0);
    }