Iterating Vectors: index range-for iterators
Iterate a vector with index access, range-for, and explicit iterators.
Three Ways to Iterate
You can walk a vector with:
- Index-based
for (size_t i = 0; i < v.size(); ++i) - Range-based
for (auto& x : v) - Iterators
for (auto it = v.begin(); it != v.end(); ++it)
Index-Based Loop
Familiar from C. Useful when you need the index alongside the value.
for (size_t i = 0; i < v.size(); ++i) {
std::cout << i << ": " << v[i] << "\n";
}All lessons in this course
- std::vector Basics: push_back size capacity
- Iterating Vectors: index range-for iterators
- Modifying Vectors: insert erase clear
- Vector vs std::array vs C Array