Are these two correct ways of iterating through a vector?

I'm not sure if both are equally valid or one should be preferred over the other.
First one is the same way as one would iterate over a static array. Second one involves iterators.

1
2
for (int i=0; i<vec.size(); i++)
    //do something with vector element by using vec[i] or vec.at(i); 



1
2
for (auto it=vec.begin(); it!=vec.end(); it++)
    //do something with vector element by using *it; 


Is the first one not a good practice for some reason? Or as long as I don't go out of bounds it's ok?

Edit: I'm using #include <vector> header file. My program has structs as the vector elements, but I believe that's not important as for the best way to iterate.
Last edited on
Both are valid, but they are not the only methods available. I myself would replace them with:

1
2
for(auto& itr : vec)
   // Do something with itr. 
Last edited on
I think both ways are valid.

Some compilers will warn you about the first loop because you are mixing signed and unsigned integers. In this particular case it probably doesn't matter but simply changing the type of i from int to something like std::size_t will get rid of the warning.

The first loop might be more convenient if are using the index for something like printing the position of each element in the vector. Similarly the second loop could be more convenient if you are using the iterator for something in the loop.
Last edited on
Thanks guys!
Topic archived. No new replies allowed.