The reason why you don’t see such practice is quite subjective and cannot have a definite answer, because I have seen many of the code which uses your mentioned way rather than
iterator style code.
Following can be reasons of people not considering
vector.size() way of looping:
- Being paranoid about calling
size()every time in the loop
condition. However either it’s a non-issue or it can be trivially
- Later changing the container from
std::vectorto other one (e.g.
list) will also demand the change of the looping mechanism,
because not every container support
size()style of looping
C++11 provides a good facility to move through the containers. That is called “range based for loop” (or “enhanced for loop” in Java).
With little code you can traverse through the full (mandatory!)
vector<int> vi; ... for(int i : vi) cout << "i = " << i << endl;