Source of vector16.cpp


  1: //vector16.cpp

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

  7: int main()
  8: {
  9:     cout << "\nThis program illustrates a vector of vectors.";
 10:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 12:     cout << "\nWe create, populate, and then display, a vector "
 13:          "(of size 3) of integer vectors.\nEach \"row\" of the "
 14:          "\"vector of vectors\" has a different length, so the "
 15:          "overall\neffect is to have a two-dimensional \"jagged "
 16:          "array\" of integers.";
 17:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 19:     cout << "\nThe first row has 4 components, the second has 10, "
 20:         "and the third has 6:\n";

 22:     vector<vector<int> > v_2d;
 23:                     //^Note this (necessary) blank space!
 24:                     //Exercise: Check what happens if it's not there.
 25:                     //Further note: Acually, with C++11, nothing happens
 26:                     //since this is no longer a problem.

 28:     vector<int> v(4, 7);
 29:     v_2d.push_back(v);
 30:     v.assign(10, 3);
 31:     v_2d.push_back(v);
 32:     v.assign(6, 5);
 33:     v_2d.push_back(v);

 35:     for (vector<vector<int> >::size_type i=0; i<v_2d.size(); i++)
 36:     {
 37:         vector<int>::iterator p = v_2d[i].begin();
 38:         while (p != v_2d[i].end()) cout << *p++ << " ";
 39:         cout << endl;
 40:     }
 41:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 42: }