C++: Vectors
Vectors are a lot like arrays, apart from they are better. You can easily change the size of them, they are dynamic etc..
To create vectors we need to include the appropriate file:
#include <vector>
Now we have done thing we can create the vector itself. This is the generalised code:
vector<datatype> name (number of elements);
For example if we wanted an int vector with 20 elements we would use something like this:
vector<int> VectorOne (20);
However when we specify a number of elements it actually creates these all for us (in this example 0-19) and sets all there values to 0. A lot of the time you won't want to specify a number of elements (if you do specify this you can change the values from zero later). Here is an example of a vector when does not specify the number of elements:
vector<int> VectorOne;
Then to add a new value to the vector which currently has no values we can use the "push_back" method. This is an example of this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> VectorOne;
VectorOne.push_back(1);
cout << VectorOne[0] << endl;
system("PAUSE");
return 0;
}
In this case it would display '1', as piece 0 of the vector now contains the value 1 (because of the push_back method).
There are loads of methods you could use, another is the resize method, in which we can resize the vector.
For example the following would create an error(as we are changing the vector so it only contains two values):
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> VectorOne;
VectorOne.push_back(4.9);
VectorOne.push_back(6.2);
VectorOne.push_back(12);
VectorOne.resize(2);
cout << VectorOne[2] << endl;
system("PAUSE");
return 0;
}
We can also remove the last value from the vector using the "pop_back" method. This for example would create an error (as there is no longer a third value):
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> VectorOne;
VectorOne.push_back(4.9);
VectorOne.push_back(6.2);
VectorOne.push_back(12);
VectorOne.pop_back();
cout << VectorOne[2] << endl;
system("PAUSE");
return 0;
}
You can apply pretty much all of the stuff you can do with normal arrays to vectors. As they work in the same way.
Back to C++

