zoukankan      html  css  js  c++  java
  • sum up elements of a C++ vector

    C++03

    1. Classic for loop:

    for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
        sum_of_elems += *it;

      2. a. 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

    C++11 and higher

    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));
    2. Using std::for_each:

      std::for_each(vector.begin(), vector.end(), [&] (int n) {
          sum_of_elems += n;
      });
    3. Using a range-based for loop:

      for (auto& n : vector)
          sum_of_elems += n;
       
  • 相关阅读:
    用两个栈实现队列
    *重建二叉树
    *链表中环的入口结点
    *复杂链表的复制
    替换空格
    python多线程文件拷贝
    进程、线程、协程
    文件处理工具sed、awk
    CentOs软件安装
    python logging模块
  • 原文地址:https://www.cnblogs.com/xxxsans/p/14411393.html
Copyright © 2011-2022 走看看