Activity 11-4 - Vectors



Vectors can be thought of as arrays that can grow (and shrink) in length as needed while your program is running.  So far, in C++ programs that you have written, the arrays that were created had a fixed length and the program could not change the length of the array once it started running.  Vectors serve the same purpose as arrays, but their length can be changed when the program is running.  In order to use vectors in your C++ programs, you need to include:
#include<vector>
using namespace std;.

Similar to arrays, vectors have a base type and will store a collection of values of its base type.  We declare a variable, v, for a vector with base type int as:

vector<int> v;

The notation vector<Base_Type> is a template class, which means you can substitute any type for the Base_Type.  Vector elements are indexed starting with 0.  The array square brackets, [ and ], can be used to read or change these elements.

Example:
v[i] = 42;
cout << "The ith element is " << v[i];

Restrictions: You can use the [ and ] to change the value of the ith element, but you cannot use this notation to initialize that element.  Thus, you can only change an element that has already been given a value.

To add an element to a vector, you will use the push_back function.  You add elements to a vector in order of positions, first at position 0, then position 1, then 2, and so forth.  The function push_back will add an element in the next available position.  Here is an example:

vector<double> sample;
sample.push_back(0.0);
sample.push_back(1.1);
sample.push_back(2.2);

These lines initialize the elements 0, 1, and 2 of the vector sample to 0.0, 1.1, and 2.2.

the number of elements in a vector is called its size.  There is a member function, size( ), that can be used to determine the size of a vector.  To display the number of elements in vector sample (size of the vector) we will use:

cout << sample.size( );

The size function returns an unsigned int, because the returned value should always be positive.

There is a vector constructor which takes one integer and will initialize the number of positions given as the argument.  For example,

vector<int> v(10);

initializes the first 10 elements of the vector v to 0.  Thus, if we put the cout << sample.size( ); after this statement we will get a size of 10.  Once this is done, then you can use the [ and ] to set other values for those elements.

for(int i = 0; i < v.size( ); i++)
    v[i] = 2*i;

Important note: It is worth noting that the number of vector elements for which memory is allocated is called the capacity of that vector. The capacity is not the same thing as the size, which is number of elements with values.  To determine the capacity of a vector, we use the capacity( ) function.

cout << v.capacity( );

will display the capacity of vector v.

Whenever a vector runs out of capacity and needs room for an additional member, the capacity is automatically increased. The increase is usually done by doubling the existing capacity, but this may not be efficient.  There are two other functions that can be used to change the capacity of a vector.  The first function is called reserve(Limit).  This function will explicitly increase the capacity by Limit.  For example:

v.reserve(32);

will set the capacity to at least 32 elements.  The following call:
v.reserve(v.size( ) + 10);

sets the capacity to at least 10 more than the number of elements currently in the vector.  Note that the reserve( ) function can increase the capacity but may not be able to decrease the capacity.  You can reduce the capacity using the resize function:

v.resize(24);

This resizes the vector to 24 elements.  In the case that there are more than 24 elements in the vector, the extra elements will be distorted.

Following is a program in which we will use a vector to read some values and to compute their average.

// P11_4.cpp - This program will ask for some values and display their average

#include<iostream>
#include<vector>
using namespace std;

int main( )
{
     vector<int> v(4);
     char ans = 'y';
     float sum = 0;
     int count = 0;

     while(ans == 'y' || ans == 'Y')
     {
             cout << "Enter an integer \n";
             cin >> v[count];
             sum += v[count];
             count++;

             cout << "Do you wish to enter a new number y/n \n";
             cin >> ans;
      }

      if(count > 0)
      {
          cout << "Average of " << count  << " numbers is " << sum/count << endl;
      }

     return 0;
}

Exercise 11.4
Copy and paste or carefully type program P11_4.cpp and compile it.  Run the program for the following cases:

1) 4 numbers:  2  2  2  2            the average in this case is 2
2) 6 numbers:  2  2  2  2  2  2    the average is 2 again
3) 8 numbers:  1  2  3  4  5  6  7  8      the average in this case is 4.5

Did you get the correct answers?

Replace the i in the statement sum/count with one of the v.size( ) or v.capacity( ) that you think should produce the correct results. Compile and run the program for the above three cases.  Did you get the correct results in all three cases?  Can you explain the reason for not getting the correct answer?