Alex Rivera | Logout

How do I iterate over a vector and also know the index of the element?

Asked 2012-09-19T13:07:43.783
59

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?

Edit
Report

2 Answers

13

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

answered 2012-09-19T13:10:26.903
-1
for (iterator it = aVector.begin(), int index= 0; it!= aVector.end(); ++it, ++index)

This will not compile. But it doesn't really matter, because as long as we are talking about std::vector then accessing by index is a simple pointer arithmetic and dereference - so in reality as fast as with the iterator. So your version 2 is OK.

I would however further optimize (if you are really concerned about speed):

for (int index = 0, size = aVector.size(); index < size; ++index)
{
    // access using []
}
answered 2012-09-19T13:13:35.693

Your Answer