They should be used whenever you have an unknown number of items all of the same type that you need to be kept in sequence and we need to accesws them by their number in the sequence.
Example: a roster of students in a class.
Quick Reference
Vectors are held in a special library and can be used in a file that has
#include <vector>at its beginning.
| Declaration | vector<type> v(initial_size); |
| Accessors | v.empty(), v.size(), v.front(), v.back(),... |
| Mutators | v.push_back(T), v.pop_back(), ... |
| Operators | v[int], v.at(int), v1=v2;, v1==v2, ... |
Details
Suppose that T is any type or class - say int, float, double, or
the name of a class, then
vector<T> v;declares a new and empty vector called v.
vector<T> v(N);declares a new vector called v with N unknown elements in it.
Given object v declared like the above:
v.empty()
v.size()
v.push_back(t)
v.pop_back()
v.front()
v.front() = expression;
v.back()
v.back() = expression;
Access the i'th item (0<=i<size()) without checking to see if it exists:
v[i]
Assign a copy of v1 to v:
v = v1
Example
Suppose that we want to input an unknown number of numbers and then print them
out forwards and then backwards, using a vector. We will push ints onto the back of a vector
called v. We will then print each item in v in turn. Finally we will print the
vector backwards. You can download the code from
[ Vector.cpp ]
but here are the highlights. First we must declare the facilities we want to use
#include <iostream.h>
#include <vector>
void print( vector<int> ) ;//utility function outputs a vector of ints
void print_backwards( vector<int>);Then we describe the main program:
int main()
{
vector<int> v;
int number;
cout <<"Input some numbers and then end the input\n";
while(cin>>number){
v.push_back(number);
}//while(more)
print(v);
print_backwards(v);
}//mainFinally the two procedures that print out the data:
void print_backwards( vector<int> a)
{
for(int i=a.size()-1; i>=0; --i)
cout << a[i] << " ";
cout << endl;
cout << "----------------"<<endl;
}//print_backwardsand
void print( vector<int> a)
{
for(int i=0; i<a.size(); ++i)
cout << a[i] << " ";
cout << endl;
cout << "----------------"<<endl;
Exercise
Down load (with a shift-click!) the above code from
[ Vector.cpp ]
, test it, and modify it to print out all the even numbered items (0,2,4,6,...)
and then all the odd ones(1,3,5,...).
Containers
A vector is a special kind of Container.
A Container is any data structure that holds a number of
objects of the same type.
Arrays
The oldest example
of a Container in C++ is an array. In C you
had arrays and you would
write code like this:
const int MAX = 10;
float a[MAX];
...
for(int i=0; i<MAX; ++i)
process(a[i]);
...Arrays are like vectors except that:
Underneath the hood
The way vectors and arrays work is best understood by looking at how they
are implemented. This means knowing what really happens when the computer
executes a piece of code which uses a vector or array. Recall that everything
inside a computer is a number. The data are numbers stored in locations. These
locations have addresses. These addresses are used by the computer to retrieve
items and to store them. A single variable is given a piece of storage when it is
declared. From
then on the program uses the address in place of the symbolic name in the program.
An array or vector is a block of similar pieces of storage. The block of storage
starts at the start of the vector itself, the next block is one piece of storage
later:
vector first item vector[0]
second item vector[1]
third item vector[2]and so on. The computer has a simple rule to find vector[i]. It looks at the item that starts at i*length_of_one_item + address_of_vector.
Hint
It helps to draw diagrams of vectors and work out by hand, on these diagrams
what an algorithm, or your program is doing. Pretending to be a computer
can teach you a lot about a complex computation.
You must be sure that all indices or subscripts stay between 0 and size()-1 inclusive.
Trying to change the size of an array does not work.
If a program compiles, loads, crashes, and there is a subscript operator ([...]) then check to see if the subscripted item has been put into the container before the subscripted element is accessed. A very common error is to declare a vector with no length and to use [...] as if it created new elements. It doesn't. Use 'push_back(..)' to add new elements to a vector.
If you are unable to show that a subscript is in range then use a condition like the following to guard thing[i] from errors:
0<= i && i < thing.size()
If a program compiles, loads and crashes and it has a pop, pop_back, function than make sure that there is an item to be "popped"! In code you can use the empty function to guard statements that contain "pop" from blowing up.
On some older compilers and libraries when you need a <string> as well as <vector> you need to
#include <string>before including <vector>. Obscure errors happened if they were in the reverse order! The older string library appeared to define some special versions of vector operators and the older compilers can not make up its mind which to use.
If the standard <vector> is not found then you are using an older C++ compiler.
You can have vectors of vectors:
vector < vector <int> > matrix;but you must put at least one space between the two ">" symbols. The following is wrong:
vector < vector <int>> matrix;
. . . . . . . . . ( end of section Errors) <<Contents | End>>
. . . . . . . . . ( end of section Errors) <<Contents | End>>
. . . . . . . . . ( end of section C++ Vectors) <<Contents | End>>
Abbreviations