I was watching a video of some code for a C++ program that counts the prime numbers from a start to an end number and stores them in a vector, but there is a point where they use the for loop from the title to display the numbers inside the vector, but it's the first time I've seen it.
I would like to know what it is for regardless of the context in which it is used (that is why I do not put any type of code) and what is the difference with the other type of for loop that I put.
Thanks in advance.
For classic:
This is the loop
for
that has been with us since the dawn of C++. In fact it is one of the characteristics inherited from C.Although this loop is quite simple to implement, it has some drawbacks:
i
size()
This loop could be improved as follows:
Now the method is no longer called
size()
on each iteration but instead we have achieved a slightly more cumbersome and ugly loop. In addition to that we have a variableend
that we have to avoid modifying at all costs.To simplify this code a bit, the C++11 standard offered us
for
range-based:This form of the loop is much more readable and eliminates the problems associated with the previous form:
size
on each iterationBut then the first
for
no longer serves any purpose?Not much less. Don't forget that
for
range-based needs a collection to iterate over. Thus, if we do not have a collection as such, we will not be able to use, at least in principle, this newfor
:Also,
for
range-based has no flexibility in determining offsets through the collection. If we need to iterate in an unconventional way (even indexes, insert decrements, ...) we will not be able to use thefor
range-based oneAnother case that cannot be addressed with the
for
range-based method is found when we want to remove elements from the collection.In some containers the method
erase
returns an iterator to the next element in the collection.Since
for
range-based doesn't let you interact with the iteration process, you can't use it in this case.Adapters for range-based for
I really have half deceived you. There are cases that can be dealt with
for
based on ranges but for this we need to adapt our collection.For example, to iterate backwards we can do the following
In this case there is also a ready-made adapter in BOOST . The example is for teaching purposes only.
As you can see, to use the
for
range-based one in particular scenarios we have to be able to create the corresponding adapter