Vectors

A vector is a meta data type. It is not an actual data type until it is qualified with the data type that makes up it's elements. A vector can store any number of values as long as they are all of the same data type. Each value or element can be accessed by it's index which is just an integer whose range starts from 0 and ends at the number of elements in the vector minus one.

An "integer vector" or "vector of integers" is what people say to refer to a type of vector denoted as vector<int> in C++. The qualifier data type for this meta data type lies in the angle brackets. The elements in a vector can also themselves be vectors: vector< vector<char> > is a perfectly valid data type.

In C++ terminology, vector is the name of a "class template". Recall that classes specify the design of data types in C++. Templates, which you will learn later on, are for expressing C++ code that operates on data types that are not yet known until used with future C++ code. So a vector is, in other words, a meta class.

Any qualified class of the vector class template will have the following operators available to it:

vectors will also contain member functions which, like the operators, allow for observing or manipulating the vector in some way.

I can go on and on about all this abstract nonsense but the best way for you to understand this is for you to see examples of code and to experiment with these examples yourself.

Here is a classic example of a program that uses a vector of double to calculate a mean value:

#include <iostream> #include <vector> using namespace std; int main() { double n, sum = 0.0; vector<double> v; while (cin >> n) v.push_back(n); for (double e : v) sum += e; cout << (sum / v.size()) << endl; return 0; }

When compiled, the program will read all the whitespace-seperated numbers that you enter from the keyboard until you press CTRL-D, then the mean value will be calculated and displayed.

It's not a very useful example of vectors, since a simpler program with the same effect could be expressed without using vectors:

#include <iostream> using namespace std; int main() { double n, sum = 0.0; while (cin >> n) sum += n; cout << (sum / n) << endl; return 0; }

But the original example shows how you can insert new elements into vectors using the push_back member function and iterate through each element using the range-based for loop.

Calculating the mean value from a vector of double can also be done using a regular for statement: for (int i = 0; i < v.size(); ++i) { sum += v[i]; } double mean = sum / v.size(); The same thing can also be done using a while statment: int i = 0; while (i < v.size()) sum += v[i++]; double mean = sum / v.size();