Iterate through a C++ Vector using a ‘for’ loop

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:

  1. Being paranoid about calling size() every time in the loop
    condition. However either it’s a non-issue or it can be trivially
  2. Preferring std::for_each() over the for loop itself
  3. 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;

Leave a Comment