且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何总结C ++向量的元素?

更新时间:2023-11-09 23:39:28

实际上有很多方法。

int sum_of_elems = 0;



C ++ 03



C++03


  1. 经典for循环:

  1. 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);
    

    重要提示:最后一个参数的类型不仅用于初始值,但对于结果类型也是如此。如果在其中放置一个int,即使向量具有浮点数,它也会累积int。如果要对浮点数求和,请将 0 更改为 0.0 0.0f (感谢nneonneo)。另请参见下面的C ++ 11解决方案。

    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及更高版本



    C++11 and higher


    1. b。即使在将来发生更改的情况下,也会自动跟踪矢量类型:

    1. b. Automatically keeping track of the vector type even in case of future changes:

    #include <numeric>
    
    sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                   decltype(vector)::value_type(0));
    


  • 使用 std :: for_each

    std::for_each(vector.begin(), vector.end(), [&] (int n) {
        sum_of_elems += n;
    });
    


  • 使用基于范围的for循环(感谢Roger Pate):

  • Using a range-based for loop (thanks to Roger Pate):

    for (auto& n : vector)
        sum_of_elems += n;