Source of vector04.cpp


  1: //vector04.cpp

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

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates push_back() for putting "
 11:         "values into a vector, and\ncontrasts the capacity of a "
 12:         "vector with its size. It also permits you to\nobserve "
 13:         "your C++ implementation's algorithms for reallocation. "
 14:         "Values are\nadded one at a time, and the size and capacity "
 15:         "are both displayed after each\nvalue is added by calls to "
 16:         "the size() and capacity() member functions.";
 17:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 19:     int size;
 20:     int numberToAdd;
 21:     cout << "\nEnter starting size for vector: ";
 22:     cin >> size;
 23:     cout << "Enter number of values to add: ";
 24:     cin >> numberToAdd;  cin.ignore(80, '\n');

 26:     //Create the vector and display the size and capacity
 27:     vector<int> v(size);
 28:     cout << "\nSize of vector to start:     " << v.size();
 29:     cout << "\nCapacity of vector to start: " << v.capacity();
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 32:     //Add values one at a time, re-displaying size
 33:     //and capacity after each value is added.
 34:     for (int i=1; i<=numberToAdd; i++)
 35:     {
 36:         v.push_back(1);
 37:         cout << "\nCurrent vector size:     " << v.size();
 38:         cout << "\nCurrent vector capacity: " << v.capacity();
 39:         cout << "\nPress Enter to continue ... ";
 40:         cin.ignore(80, '\n');
 41:     }
 42: }