How do I iterate over a vector and also know the index of the element?
The answer is in the question - "know what index the element is in.".
So -
for (int index = 0; index < aVector.size(); ++index)
{
// access using []
}
Performance-wise they're the same (but you can always profile yourself).
For a vector or other random-access container, it makes little difference. I would probably choose the second because it's easier to read, and is probably marginally faster since there's only one loop variable to update. Another alternative is:
for (auto it = aVector.begin(); it != aVector.end(); ++it) {
int index = std::distance(aVector.begin(), it);
}
For non-random-access containers, []
isn't available, and std::distance
is inefficient; in that case, if you need the index, the first method would be better (although you'll need to fix it so it doesn't try to declare two differently-typed variables in the for-initialiser).