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