1: //accumulate2b.cpp
3: #include <iostream>
4: #include <vector>
5: #include <numeric>
6: #include <functional>
7: using namespace std;
9: /**
10: Finds the product of two integers.
11: Pre:\n a and b contain integer values.
12: Post:\n Returns the product of a and b.
13: */
14: int product
15: (
16: int a, //in
17: int b //in
18: )
19: {
20: return a*b;
21: }
23: int main()
24: {
25: cout << "\nThis program illustrates the use of the STL accumulate() "
26: "algorithm (expanded\nversion) from <numeric> to find the "
27: "product of integers in a vector, this time\nusing a built-in "
28: "STL function object to compute the product of two integers.";
29: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
31: int a[] = {2, 4, 6, 8, 10};
32: vector<int> v(a, a+5);
34: cout << "\nHere are the integer values in the vector:\n";
35: for (vector<int>::size_type i=0; i<v.size(); i++)
36: cout << v.at(i) << " ";
37: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
39: cout << "\nThe product of these values is "
40: << accumulate(v.begin(), v.end(), 1, multiplies<int>())
41: << ".";
42: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
44: cout << "\nThe product of the middle three values and an intial "
45: "value of -5 is "
46: << accumulate(v.begin()+1, v.end()-1, -5, multiplies<int>())
47: << ". ";
48: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
50: cout << "\nThe product of the values in an empty range, with "
51: "an intial value of 22, is "
52: << accumulate(v.begin(), v.begin(), 22, multiplies<int>())
53: << ".";
54: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
55: }