Purpose of Iterators?

I am not really understanding the purpose of an iterator.
What is the difference between these two:

for(int i = vector.begin(); i != vector.end(); i++)

and

for(vector<int>::iterator it = vector.begin(); it != vector.end(); it++)

To me, it seems like they both have the same function but one is much less typing and easier to read. What is the practical use of iterators?
Neither compiles, but the second one would if the variable were not named "vector".

1
2
3
4
5
6
7
8
// Given a vector:
std::vector<int> v; // Assume it is filled out

for( int i = 0; i < v.size(); ++i )  // (1)

// vs.

for( std::vector<int>::iterator i = v.begin(); i != v.end(); ++i )  // (2) 


(1) is a compiler warning, because vector<>::size() returns a vector<>::size_type,
which is unsigned, whereas int is signed, so you'll get a compiler warning about a
signed-vs-unsigned comparison.

(1) can be fixed portably by:

 
for( std::vector<int>::size_type i = 0; i < v.size(); ++i ) 


At which point it is as long as (2), but more prone to error since it is easy to
make up integer numbers, have off-by-one errors, etc.

(2) is portable, and also works (by changing only the type of i) for all other
STL containers. (1) works only for containers that support random access
iterators (which limits you to std::vector and std::deque, basically).

(2) is also very hard to get wrong -- it's hard to be off-by-one or walk off
the end of the container.

In general, iterators:
1) are harder to get wrong than indices;
2) work for all containers
Topic archived. No new replies allowed.