I need to access each element in a vector and also know what index the element is in.
So far I could come up with two ways
for (iterator it= aVector.begin(), int index= 0; it!= aVector.end(); ++it, ++index)
leaving the type signature. also it looks like i can't use auto
for (int index = 0; index < aVector.size(); ++index)
{
// access using []
}
Which one is more efficient or is there a better way to do this?
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).