Source of count_if1a.cpp


  1: //count_if1a.cpp

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

  8: /**
  9: Determines if an integer is divisible by 3.
 10: Pre:\n n contains an integer.
 11: Post:\n Returns true if n is divisible by 3, and otherwise false.
 12: */
 13: bool isDivisibleByThree
 14: (
 15:     int n //in
 16: )
 17: {
 18:     return (n%3 == 0);
 19: }

 21: int main()
 22: {
 23:     cout << "\nThis program illustrates the use of the STL count_if() "
 24:         "algorithm to count the\nnumber of integer values in a vector "
 25:         "of integers that are divisible by 3.";
 26:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 28:     int a1[] ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
 29:     vector<int> v1(a1, a1+12);
 30:     cout << "\nHere are the contents of v1:\n";
 31:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 32:         cout << v1.at(i) << " ";
 33:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 35:     cout << "\nThe number of values in v1 that are divisible by 3 is "
 36:         << (int)count_if(v1.begin(), v1.end(), isDivisibleByThree) << ".";
 37:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 39:     int a2[] ={10, 20, 40, 50, 70, 80, 100, 110, 130, 140};
 40:     vector<int> v2(a2, a2+10);
 41:     cout << "\nHere are the contents of v2:\n";
 42:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 43:         cout << v2.at(i) << " ";
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     cout << "\nThe number of values in v1 that are divisible by 3 is "
 47:         << (int)count_if(v2.begin(), v2.end(), isDivisibleByThree) << ".";
 48:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 49: }