Posted February 1, 2011 by Spyros

# How to Use C++ Vectors of The Standard Template Library(STL)

As you can understand, the STL vectors is a pretty large c++ subject on its own. Of course, i won’t be covering eveything about them in this post. My intention is to give you a basic insight and in later posts write more about it (according to what you may want to ask for, in example).

In short, vectors are part of the c++ standard template library and were created as a means of handling complex data strcutures, without us having to worry about memory management. As you know, arrays in C/C++ have a fixed length, specified upon creation. If we need to add or remove elements from an array, we cannot really do that. To achieve that, we need to resort to techniques like dynamically allocating memory (using malloc() for instance), maybe also creating linked lists and stuff.

Thankfully, STL comes to the rescue. Using C++ vectors, we no more need to allocate and deallocate memory to handle our dynamic data structures, because STL does the dirty work for us. Let’s take a look at some basic vectors code, defining an integer vector :

```
#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

int main()
{
vector<int> v(2,3) ;

v.insert(v.begin(), 2, 1);

for (vector<int>::iterator i = v.begin(); i != v.end(); i++)
cout << *i << endl;
}
```

We need to include vector.h to work with vectors (also, if we want to create a string vector, we need to include string.h). In the beginning, we create an integer vector, a container that has a starting number of elements, defined in its constructor. In this example, we specify v(2, 3), which means that we need a vector that has 2 elements, each one having the value of 3. Therefore, our array now is like {3, 3}. Next, we do something that we would not be able to do using a simple array. We insert a new element to our vector. We specify that we want to insert that before the first element (v.begin() is a pointer to the first element). We insert 2 elements, each one having the value 1. Our new array is now {1, 1, 3, 3}.

Just to test this, we do a simple iteration of the vector, using an iterator that the vector library defines in its scope. It is, in fact, an internal vector type that is used as a template variable, so that we get a pointer to a vector element. So, starting from the first element(v.begin()), we reach the last element(v.end()) and we just print the contents of the iterator (being a pointer).