Noeud:accumulate, Noeud « Next »:, Noeud « Previous »:partition, Noeud « Up »:Generic Algorithms and Function Objects



accumulate

Simple numerical processing is provided by accumulate. There are two forms that we should be aware of. The first takes some initial value, and computes the sum of this value with the elements in the range that were passed in:

     T accumulate(InputIterator beg,
                 InputIterator end, T val);
     

The second form of accumulate accepts not only an initial value and a range, but also a binary function operator, so that we aren't restricted to just making a sum:

     T accumulate(InputIterator beg,
                 InputIterator end,
                 T val, BinaryFunc op);
     

Both of these algorithms are illustrated below:

     /* generic7.cc
      * Compiled using g++ generic7.cc -o generic7
      * Run using ./generic7 */
     
     #include <vector>
     #include <algorithm>
     #include <functional>
     #include <numeric>
     
     int main()
     {
       std::vector<int> v;
       for (int i=0; i<10; i++)
         v.push_back(i+1);
       cout << accumulate(v.begin(), v.end(), 0) << endl
            << accumulate(v.begin(), v.end(), 1, multiplies<int>());
       return 0;
     }
     
     Example 3.25: generic7.cc
     

The output is trivial, and involves printing out 55 (starting at 1 and adding each number through to 10) and 3628800 (1 through to 10, but instead of adding, we use multiplication). We've given 1 as the value to the second accumulate call because it's the identity operator for multiplication.