How to iterate over a vector?

If you have access to C++11 you can use range-based for loops

for (auto i : v)

Otherwise you should use begin() and end()

for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i)

You can also use std::begin and std::end (these require C++11 as well)

for (std::vector<int>::iterator i = std::begin(v); i != std::end(v); ++i)

begin will return an iterator to the first element in your vectorend will return an iterator to one element past the end of your vector. So the order in which you get the elements iterating this way is both safe and defined.

Leave a Comment