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

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


当前回答

c++ 0 x只:

vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;

这类似于其他地方提到的BOOST_FOREACH,与与accumulate或for_each一起使用的有状态函子相比,在更复杂的情况下具有同样的清晰性。

其他回答

似乎没有人能解决向量中可以有NaN值的元素求和的情况,例如numerical_limits<double>::quite_NaN()

我通常会遍历元素并直接检查。

vector<double> x;

//...

size_t n = x.size();

double sum = 0;

for (size_t i = 0; i < n; i++){

  sum += (x[i] == x[i] ? x[i] : 0);

}

它一点都不花哨,也就是说,没有迭代器或任何其他技巧,但我是这样做的。有时,如果在循环中有其他事情要做,我想让代码更具可读性,我就写

double val = x[i];

sum += (val == val ? val : 0);

//...

在循环中,如果需要重用val。

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

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

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

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 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()); 这个函数还有其他重载,你甚至可以并行运行,如果你有一个大的集合,你想快速得到结果。

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

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