Vector constructors

Syntax:

    #include <vector>
    using namespace std;
    vector();
    vector( const vector& c );
    vector( size_type num, const TYPE& val = TYPE() );
    template< typename input_iterator >
    vector( input_iterator start, input_iterator end );
    ~vector();

The default vector constructor takes no arguments, creates a new instance of that vector.

The second constructor is a default copy constructor that can be used to create a new vector that is a copy of the given vector c.

The third constructor creates a vector with num objects. If val is specified, each of those objects will be given that value, otherwise, those objects are given TYPE's default constructor's value. For example, the following code creates a vector consisting of five copies of the integer 42:

   vector<int> v1( 5, 42 );

The last constructor creates a vector that is initialized to contain the elements between start and end. For example:

   // create a vector of random integers
   cout << "original vector: ";
   vector<int> v;
   for( int i = 0; i < 10; ++i ) {
     int num = (int) rand() % 10;
     cout << num << " ";
     v.push_back( num );
   }
   cout << endl;
 
   // find the first element of v that is even
   vector<int>::iterator iter1 = v.begin();
   while( iter1 != v.end() && *iter1 % 2 != 0 ) {
     ++iter1;
   }
 
   // find the last element of v that is even
   vector<int>::iterator iter2 = v.end();
   do {
     --iter2;
   } while( iter2 != v.begin() && *iter2 % 2 != 0 );
 
   // only proceed if we find both numbers
   if( iter1 != v.end() && iter2 != v.begin() ) {
     cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 
     cout << "new vector: ";
     vector<int> v2( iter1, iter2 );
     for( int i = 0; i < v2.size(); ++i ) {
       cout << v2[i] << " ";
     }
     cout << endl;
   }

When run, this code displays the following output:

   original vector: 1 9 7 9 2 7 2 1 9 8
   first even number: 2, last even number: 8
   new vector: 2 7 2 1 9

All of these constructors run in linear time except the first, which runs in constant time.

The default destructor is called for each element when the vector is destroyed.