Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need iterator when using ranged-based for loops

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?

like image 862
小太郎 Avatar asked Aug 05 '11 07:08

小太郎


People also ask

Does a range-based for loop use iterators?

Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable.

How does range-based for loop work?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Are iterators used in for-each loops C++?

Working of the foreach loop in C++ So basically a for-each loop iterates over the elements of arrays, vectors, or any other data sets. It assigns the value of the current element to the variable iterator declared inside the loop.

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).


1 Answers

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.

like image 142
Nawaz Avatar answered Sep 21 '22 20:09

Nawaz