Source of merge2a.cpp


  1: //merge2a.cpp

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

  8: /**
  9: Tests if one integer has a smaller digit sum than another.
 10: Pre:\n i1 and i2 have been initialized and i1, i2 are both > 0.
 11: Post:\n Returns true if sum of the digits in i1 is < sum of digits
 12: in i2, and otherwise returns false.
 13: */
 14: bool hasSmallerDigitSum
 15: (
 16:     int i1, //in
 17:     int i2  //in
 18: )
 19: {
 20:     int digitSum1 = 0;
 21:     while (i1 != 0)
 22:     {
 23:         digitSum1 += i1 % 10;
 24:         i1 /= 10;
 25:     }

 27:     int digitSum2 = 0;
 28:     while (i2 != 0)
 29:     {
 30:         digitSum2 += i2 % 10;
 31:         i2 /= 10;
 32:     }
 33:     return digitSum1 < digitSum2;
 34: }

 36: int main()
 37: {
 38:     cout << "\nThis program illustrates the use of the STL merge() "
 39:         "algorithm (extended\nversion) to merge two ordered ranges of "
 40:         "integer values from two different\nvectors of integers into a "
 41:         "single ordered range of values within another\nvector of "
 42:         "integers. The order of values is determined by one value "
 43:         "preceding \nanother if and only if the first has a smaller "
 44:         "digit sum than the second.";
 45:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 47:     int a1[] = {11, 41 , 45, 59, 98};
 48:     vector<int> v1(a1, a1+5);
 49:     cout << "\nHere are the contents of v1:\n";
 50:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 51:         cout << v1.at(i) << " ";
 52:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 54:     int a2[] = {121, 13, 6, 52, 44, 36, 28, 69};
 55:     vector<int> v2(a2, a2+8);

 57:     cout << "\nHere are the contents of v2:\n";
 58:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 59:         cout << v2.at(i) << " ";
 60:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 62:     vector<int> v3(15);
 63:     cout << "\nHere are the contents of v3:\n";
 64:     for (vector<int>::size_type i=0; i<v3.size(); i++)
 65:         cout << v3.at(i) << " ";
 66:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 68:     cout << "\nNow merge the contents of v1 and v2 into v3.";
 69:     merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin(),
 70:         hasSmallerDigitSum);
 71:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 73:     cout << "\nHere are the revised contents of v3:\n";
 74:     for (vector<int>::size_type i=0; i<v3.size(); i++)
 75:         cout << v3.at(i) << " ";
 76:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 77: }