The cleanest way of iterating through a vector is via iterators:
for (auto it = begin (vector); it != end (vector); ++it) {
it->doSomething ();
}
or (equivalent to the above)
for (auto & element : vector) {
element.doSomething ();
}
Prior to C++0x, you have to replace auto by the iterator type and use member functions instead of global functions begin and end.
This probably is what you have seen. Compared to the approach you mention, the advantage is that you do not heavily depend on the type of vector
. If you change vector
to a different "collection-type" class, your code will probably still work. You can, however, do something similar in Java as well. There is not much difference conceptually; C++, however, uses templates to implement this (as compared to generics in Java); hence the approach will work for all types for which begin
and end
functions are defined, even for non-class types such as static arrays. See here: How does the range-based for work for plain arrays?
std::vector<int>::size_type i = 0;
, though, or perhapsstd::vector<int>::iterator it = vector.begin();
?std::vector
?, the actual Q being asked here is: Is there any reason I don't see thisin C++? Is it bad practice? aka Why do I always see code in C++ which uses iterators while iterating overstd::vector
?