Source of inplace_merge2a.cpp


  1: //inplace_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 "
 39:         "inplace_merge() algorithm\n(extended version) to merge two "
 40:         "ordered ranges of integer values in the\nsame vector into a "
 41:         "single ordered range of values within that same vector.\nThe "
 42:         "order of values is determined by one value preceding another "
 43:         "if and\nonly if the first has a smaller digit sum than the "
 44:         "second.";
 45:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 47:     int a[] = {11, 41 , 36, 59, 98, 21, 13, 6, 52, 44, 28, 69};
 48:     vector<int> v(a, a+12);

 50:     cout << "\nHere are the contents of v:\n";
 51:     for (vector<int>::size_type i=0; i<v.size(); i++)
 52:         cout << v.at(i) << " ";
 53:     cout << "\nNote that the first five values form the first range, "
 54:         "\nand the rest of the values form the second range.";
 55:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 57:     inplace_merge(v.begin(), v.begin()+5, v.end(), hasSmallerDigitSum);

 59:     cout << "\nNow we perform the \"in place merge\".";
 60:     cout << "\nHere are the revised contents of v:\n";
 61:     for (vector<int>::size_type i=0; i<v.size(); i++)
 62:         cout << v.at(i) << " ";
 63:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 64: }