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.
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.