For an introduction to vectors, refer to the c++ reference on this very site (saves me typing)
http://www.cplusplus.com/reference/stl/vector/
An iterator is a STL object that behaves like a pointer.
Consider the following standard C/C++ code:
1 2 3 4 5 6 7 8 9
|
#define ARRAY_MAX 5
int int_array[ARRAY_MAX] = {1,2,3,4,5}; //an array
int *int_ptr; // a pointer to iterate through the array
for (int_ptr = int_array; int_ptr != int_array+ARRAY_MAX; ++int_ptr)
{
cout << *int_ptr << endl;
}
|
we have an array. We want to loop through the array, so we declare a pointer of the correct type
int *int_ptr;
and set it to the start of the array
int_ptr = int_array;
.
Each time round the loop we get the current value at the pointer and do something with it
cout << *int_ptr << endl;
.
We make sure that we don't step past the end of the array
int_ptr < int_array+ARRAY_MAX;
and we update the iterator each time round the loop
++int_ptr
The C++ STL designers have developed a direct replacement template class for the standard array called the vector.
The vector has what is called an interator - which is as we have said is a type of pointer.
The vector has a class method called
begin() which returns an iterator or pointer
to the first elemen in the vector.
It also has a method called
end() which returns a pointer to the element
which is ONE past the last element in the vector.
To get the elecment currently being pointed at the iterator we use the familiar
*pointer
notation, and to increment the iterator we use the familiar
++pointer notation.
So your code using vectors would be :
1 2 3 4 5 6 7
|
//print out the vector
vector<string>::iterator itr; //declare an iterator of the right type - in this case string
//loop through array vector using iterator
for (itr = array.begin(); itr != array.end(); ++itr)
{
cout << *itr << " ";
}
|
The vector is a direct replacement for the standard array and much better and safer to use.
There are other '
containers' int the STL, like queues, stack, lists,........
Does that make sense?