Source of accumulate1a.cpp


  1: //accumulate1a.cpp

  3: #include <iostream>
  4: #include <vector>
  5: #include <numeric>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the use of the STL accumulate() "
 11:         "algorithm (default\nversion) from <numeric> to find the sum of "
 12:         "integer values stored in a vector.";
 13:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 15:     int a[] = {2, 4, 6, 8, 10};
 16:     vector<int> v(a, a+5);

 18:     cout << "\nHere are the integer values in the vector:\n";
 19:     for (vector<int>::size_type i=0; i<v.size(); i++)
 20:         cout << v.at(i) << " ";
 21:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 23:     cout << "\nThe sum of these values is "
 24:          << accumulate(v.begin(), v.end(), 0) << ".";
 25:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 27:     cout << "\nThe sum of the middle three values and an intial "
 28:             "value of -5 is "
 29:          << accumulate(v.begin()+1, v.end()-1, -5) << ".";
 30:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 32:     cout << "\nThe sum of the values in an empty range, with "
 33:             "an intial value of 22, is "
 34:          << accumulate(v.begin(), v.begin(), 22) << ".";
 35:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 36: }