Need iterator when using ranged-based for loops

小太郎 picture 小太郎 · Aug 5, 2011 · Viewed 45.5k times · Source

Currently, I can only do ranged based loops with this:

for (auto& value : values)

But sometimes I need an iterator to the value, instead of a reference (For whatever reason). Is there any method without having to go through the whole vector comparing values?

Answer

Nawaz picture Nawaz · Aug 5, 2011

Use the old for loop as:

for (auto it = values.begin(); it != values.end();  ++it )
{
       auto & value = *it;
       //...
}

With this, you've value as well as iterator it. Use whatever you want to use.


EDIT:

Although I wouldn't recommended this, but if you want to use range-based for loop (yeah, For whatever reason :D), then you can do this:

 auto it = std::begin(values); //std::begin is a free function in C++11
 for (auto& value : values)
 {
     //Use value or it - whatever you need!
     //...
     ++it; //at the end OR make sure you do this in each iteration
 }

This approach avoids searching given value, since value and it are always in sync.