Source of list04.cpp


  1: //list04.cpp

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

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates push_back() and push_front() "
 11:         "for putting values\ninto a list, and shows the size of the "
 12:         "list after each call to either of\nthese member functions. ";
 13:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 15:     int size;
 16:     cout << "\nEnter starting size for list: ";
 17:     cin >> size;

 19:     //Create the list
 20:     list<int> lst(size);

 22:     //Add values to back of list, one at a time.
 23:     cout << "\nEnter number of values to add to back: ";
 24:     int numberToAddToBack;
 25:     cin >> numberToAddToBack;  cin.ignore(80, '\n');

 27:     cout << "\nWe will now add the values 1 to " << numberToAddToBack
 28:         << " to the back of the list.";
 29:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 30:     for (int i=1; i<=numberToAddToBack; i++) lst.push_back(i);
 31:     cout << "\nCurrent list size: " << lst.size();
 32:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 34:     //Add values to front of list, one at a time.
 35:     cout << "\nEnter number of values to add to front: ";
 36:     int numberToAddToFront;
 37:     cin >> numberToAddToFront;  cin.ignore(80, '\n');

 39:     cout << "\nWe will now add the values 1 to " << numberToAddToFront
 40:         << " to the front of the list.";
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 42:     for (int i=1; i<=numberToAddToFront; i++) lst.push_front(i);
 43:     cout << "\nCurrent list size: " << lst.size();
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     cout << "\nContents of the list: ";
 47:     list<int>::iterator p = lst.begin();
 48:     while (p != lst.end()) cout << *p++ << " ";
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 50: }