Source of list17.cpp


  1: //list17.cpp

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

  7: bool hasSmallerDigitSum
  8: (
  9:     int i1, //in
 10:     int i2  //in
 11: )
 12: /**<
 13: Test if one integer has a smaller digit sum than another.
 14: @return true if sum of the digits in i1 is < sum of digits
 15: in i2, and otherwise returns false.
 16: @param i1 An integer.
 17: @param i2 An integer.
 18: @pre i1 and i2 have been initialized and i1, i2 are both > 0.
 19: @post No side effects. 
 20: */
 21: {
 22:     int digitSum1 = 0;
 23:     while (i1 != 0)
 24:     {
 25:         digitSum1 += i1 % 10;
 26:         i1 /= 10;
 27:     }

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

 38: int main()
 39: {
 40:     cout << "\nThis program illustrates the reverse() and sort()"
 41:         "\nmember functions for list objects.";
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     int a[] = {17, 12, 14, 19, 23, 15, 61, 20, 81, 11};
 45:     list<int> lst(a, a+10);
 46:     cout << "\nFor the starting list we have:";
 47:     cout << "\nSize = " << lst.size();
 48:     cout << "\nContents: ";
 49:     list<int>::iterator p = lst.begin();
 50:     while (p!= lst.end())  cout << *p++ << " ";
 51:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 53:     cout << "\nNow we sort the list in ascending order:";
 54:     lst.sort();
 55:     p = lst.begin();
 56:     cout << "\nSize = " << lst.size();
 57:     cout << "\nContents: ";
 58:     while (p!= lst.end())  cout << *p++ << " ";
 59:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 61:     cout << "\nNext we reverse the list, which will give the values "
 62:         "in descending order:";
 63:     lst.reverse();
 64:     p = lst.begin();
 65:     cout << "\nSize = " << lst.size();
 66:     cout << "\nContents: ";
 67:     while (p!= lst.end())  cout << *p++ << " ";
 68:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 70:     cout << "\nFinally we sort the list according to the criterion "
 71:         "that one value\ncomes before another if and only if it has "
 72:         "a smaller digit sum:";
 73:     lst.sort(hasSmallerDigitSum);
 74:     p = lst.begin();
 75:     cout << "\nSize = " << lst.size();
 76:     cout << "\nContents: ";
 77:     while (p!= lst.end())  cout << *p++ << " ";
 78:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 79: }