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
fixed
- Preferring
std::for_each()
over the for
loop itself
- Later changing the container from
std::vector
to other one (e.g.
map
, 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!) std::vector
:
vector<int> vi;
...
for(int i : vi)
cout << "i = " << i << endl;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…