【问题标题】:Vector sum in C++ design strategy [duplicate]C ++设计策略中的向量和[重复]
【发布时间】:2011-03-26 16:40:12
【问题描述】:

可能重复:
sum of elements in a std::vector

我想对 std::vector 的项目求和

例如

 std::vector<int > MYvec;
 /*some push backs*/

 int x=sum(MYVec); //it should give sum of all the items in the vector

sum函数怎么写?

我试过了

 int sum(const std::vector<int> &Vec)
 {
    int result=0;
    for (int i=0;i<Vec.size();++i)
      result+=Vec[i];
    return result;
 }

但是我不喜欢我的方法

【问题讨论】:

    标签: c++ stl vector


    【解决方案1】:

    尝试使用 C++ 标准库中的accumulate。 像这样的:

    #include <vector>
    #include <numeric>
    
    // Somewhere in code...
    std::vector<int> MYvec;
    /*some push backs*/
    
    int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
    

    【讨论】:

    【解决方案2】:

    你应该使用std::accumulate

    int main() {
      std::vector<int> vec;
      // Fill your vector the way you like
      int sum = std::accumulate(vect.begin(), vect.end(), 0); // 0 is the base value
      std::cout << sum << std::endl;
      return 0;
    }

    【讨论】:

      【解决方案3】:

      是否有一个 std::accumulate 函数可以做到这一点?

      【讨论】:

      • 差不多。 std::accumulate 使用 operator+,而不是 operator+=。但在任何理智的程序中,这不应该有什么不同,而ints 绝对不会。
      【解决方案4】:

      您必须遍历数组中的所有项目并计算总和,没有更简单的方法。我猜循环是最简单的

      int sum = 0;
      for(unsigned i = 0; i < Myvec.size(); i++){
         sum += MYvec[i];
      }
      

      【讨论】:

        猜你喜欢
        • 2016-02-20
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-22
        • 2020-01-19
        • 2014-09-30
        • 1970-01-01
        相关资源
        最近更新 更多