3 minute briefing on vectors

As promised, let me talk about fancier ways of making arrays, namely vectors. We just “learned” that you can create an array using [] and that you can use those [] to address a particular element in the array:

int a[10];

But what if I don’t know how large my array should be beforehand? That is why we have vectors. Check this out:

vector<int> a;

The above code creates a vector that will contain ints called a and afterwards we set it’s size to 10. Once that is done the variable a behaves exactly like a classic array of that size. Well not exactly because vector has a couple of extra powers:

vector<int> a;
int i;
a.clear(); // removes every element from the vector
a.push_back(4); // adds the value 4 to the end of the vector
i=a.size(); // .size() will tell you how long the vector is, in this case 1, so that now i has the value of 1

And to blow your mind, vectors can be nested to create multidimensional structures:

vector<vector<int> > a;
//code to initialize every thing properly
//which I will not put here right now
//Note the space in between the two right-angle brackets "> >" above. This is necessary*.

In case you wanted to make something like a checker board …

Cheers Arend

Leave a Reply