Source of deque08.cpp


  1: //deque08.cpp

  3: #include <iostream>
  4: #include <deque>
  5: using namespace std;

  7: int numberOfOddValues
  8: (
  9:     const deque<int>& d //in
 10: );
 11: /**<
 12: Counts the odd integers in a deque of integers.
 13: @return The number of odd integer values in the deque.
 14: @param d A deque of integers.
 15: @pre d has been initialized.
 16: @post No side effects.
 17: */

 19: int main()
 20: {
 21:     cout << "\nThis program illustrates a typical use of a const "
 22:         "iterator of the deque class.";
 23:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 25:     cout << "\nHere are the contents of a deque of size 12:\n";
 26:     int a[] = {1, 4, 6, 8, 11, 13, 15, 16, 19, 20, 23, 25};
 27:     deque<int> d(a, a+12);
 28:     deque<int>::iterator p = d.begin();
 29:     while (p != d.end()) cout << *p++ << " ";
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 32:     cout << "\nThe number of odd values in the deque is "
 33:         << numberOfOddValues(d) << ".\n";
 34:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 35: }


 38: int numberOfOddValues
 39: (
 40:     const deque<int>& d //in
 41: )
 42: {
 43:     int oddCount = 0;
 44:     //Since d is a "const" input parameter, you must use
 45:     //a const_iterator inside the function to access d. 
 46:     deque<int>::const_iterator p = d.begin();
 47:     while (p != d.end())
 48:     {
 49:         if (*p % 2 == 1) ++oddCount;
 50:         ++p;
 51:     }
 52:     return oddCount;
 53: }