Source of vector01.cpp


  1: //vector01.cpp

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

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates all constructors of the STL "
 11:         "vector container class,\nas well as the empty() and size() "
 12:         "member functions, the size_type typedef, and\nthe v[i] method "
 13:         "of accessing vector components.";
 14:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 16:     //Create an empty vector
 17:     vector<int> v1;
 18:     if (v1.empty()) cout << "\nv1 is empty.\n";
 19:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 21:     //Create a vector filled with the default component-type value
 22:     vector<int> v2(5);
 23:     cout << "\nContents of v2: ";
 24:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 25:         cout << v2[i] << " ";
 26:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 28:     //Create a vector filled with a specific component-type value
 29:     vector<double> v3(4, 3.14);
 30:     cout << "\nContents of v3: ";
 31:     for (vector<double>::size_type i=0; i<v3.size(); i++)
 32:         cout << v3[i] << " ";
 33:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 35:     //Create a vector using pointers to an integer array
 36:     int a[] = {2, 4, 6, 8, 10, 12};
 37:     vector<int> v4(a, a + sizeof(a)/sizeof(int));
 38:     cout << "\nContents of v4: ";
 39:     for (vector<int>::size_type i=0; i<v4.size(); i++)
 40:         cout << v4[i] << " ";
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 43:     //Create a vector using pointers to a C-string
 44:     char s[] = "Hello";
 45:     vector<char> v5(s, s + strlen(s));
 46:     cout << "\nContents of v5: ";
 47:     for (vector<char>::size_type i=0; i<v5.size(); i++)
 48:         cout << v5[i] << " ";
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 51:     //Create a new vector as a copy of an existing vector
 52:     vector<double> v6(v3); //or vector<double> v6 = v3;
 53:     cout << "\nContents of v6 same as those of v3: ";
 54:     for (vector<double>::size_type i=0; i<v6.size(); i++)
 55:         cout << v6[i] << " ";
 56:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 57: }