I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter of the for
loop is always something based on the vector. In Java I might do something like this with an ArrayList:
for(int i=0; i < vector.size(); i++){
vector[i].doSomething();
}
Is there a reason I don't see this in C++? Is it bad practice?
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:
size()
every time in the loop
condition. However either it's a non-issue or it can be trivially
fixedstd::for_each()
over the for
loop itselfstd::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 loopingC++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;