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

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


当前回答

实际上有相当多的方法。

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()); 这个函数还有其他重载,你甚至可以并行运行,如果你有一个大的集合,你想快速得到结果。

其他回答

实际上有相当多的方法。

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()); 这个函数还有其他重载,你甚至可以并行运行,如果你有一个大的集合,你想快速得到结果。

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

#include <numeric>
cout << accumulate(A.begin(), A.end(), 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);
    }

也可以像这样使用std::valarray<T>

#include<iostream>
#include<vector>
#include<valarray>

int main()
{
    std::vector<int> seq{ 1,2,3,4,5,6,7,8,9,10 };
    std::valarray<int> seq_add{ seq.data(), seq.size() };
    std::cout << "sum = " << seq_add.sum() << "\n";

    return 0;
}

有些人可能不觉得这种方法有效,因为valarray的大小需要和vector的大小一样大,并且初始化valarray也需要时间。

在这种情况下,不要使用它,把它作为另一种对序列求和的方式。

似乎没有人能解决向量中可以有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。