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

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


当前回答

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

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

其他回答

实际上有相当多的方法。

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);
    }

使用inclinclve_scan (c++ 17及以上):

这样做的好处是可以得到一个向量中前“N”个元素的和。下面是代码。在评论中解释。

要使用inclinclve_scan,需要包含“numeric”标头。

    //INPUT VECTOR
    std::vector<int> data{ 3, 1, 4, 1, 5, 9, 2, 6 };

    //OUTPUT VECTOR WITH SUMS
    //FIRST ELEMENT - 3 
    //SECOND ELEMENT - 3 + 1 
    //THIRD ELEMENT - 3 + 1 + 4 
    //FOURTH ELEMENT - 3 + 1 + 4 + 1
    // ..
    // ..
    //LAST ELEMENT - 3 + 1 + 4 + 1 + 5 + 9 + 2 + 6
    std::vector<int> sums(data.size());

    //SUM ALL NUMBERS IN A GIVEN VECTOR.
    inclusive_scan(data.begin(), data.end(),
        sums.begin());

    //SUM OF FIRST 5 ELEMENTS.
    std::cout << "Sum of first 5 elements :: " << sums[4] << std::endl;

    //SUM OF ALL ELEMENTS
    std::cout << "Sum of all elements :: " << sums[data.size() - 1] << std::endl;

还有一种重载,可以指定执行策略。顺序执行或并行执行。需要包括“执行”头。

    //SUM ALL NUMBERS IN A GIVEN VECTOR.
    inclusive_scan(std::execution::par,data.begin(), data.end(),
        sums.begin());

使用reduce:

我在答案中没有注意到的另一个选项是使用c++17中引入的std::reduce。

但是你可能会注意到很多编译器不支持它(GCC 10以上可能就不错了)。但最终支持会来的。

使用std::reduce,优势在于使用执行策略。指定执行策略可选。当指定执行策略为std::execution::par时,算法可能会使用硬件并行处理能力。当使用大尺寸向量时,增益可能会更明显。

例子:

//SAMPLE
std::vector<int> vec = {2,4,6,8,10,12,14,16,18};
    
//WITHOUT EXECUTION POLICY
int sum = std::reduce(vec.begin(),vec.end());
    
//TAKING THE ADVANTAGE OF EXECUTION POLICIES
int sum2 = std::reduce(std::execution::par,vec.begin(),vec.end());
    
std::cout << "Without execution policy  " << sum << std::endl;
std::cout << "With execution policy  " << sum2 << std::endl;

std::reduce需要<numeric>报头。 和'<execution>'用于执行策略。

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);