1: //vector08.cpp
3: #include <iostream>
4: #include <vector>
5: using namespace std;
7: int numberOfOddValues
8: (
9: const vector<int>& v //in
10: );
11: /**<
12: Counts the odd integers in a vector of integers.
13: @return The number of odd integer values in a vector of integers.
14: @param v A vector of integers.
15: @pre v has been initialized.
16: @post Returns the number of odd integer values in v.
17: */
19: int main()
20: {
21: cout << "\nThis program illustrates a typical use of a const "
22: "iterator of the vector class.";
23: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
25: cout << "\nHere are the contents of a vector of size 12:\n";
26: int a[] = {1, 4, 6, 8, 11, 13, 15, 16, 19, 20, 23, 25};
27: vector<int> v(a, a+12);
28: vector<int>::iterator p = v.begin();
29: while (p != v.end()) cout << *p++ << " ";
30: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
32: cout << "\nThe number of odd values in the vector is "
33: << numberOfOddValues(v) << ".\n";
34: cout << "Press Enter to continue ... "; cin.ignore(80, '\n');
35: }
38: int numberOfOddValues
39: (
40: const vector<int>& v //in
41: )
42: {
43: int oddCount = 0;
44: //Since v is a "const" input parameter, you must use
45: //a const_iterator inside the function to access v.
46: vector<int>::const_iterator p = v.begin();
47: while (p != v.end())
48: {
49: if (*p % 2 == 1) ++oddCount;
50: ++p;
51: }
52: return oddCount;
53: }