'Difference between range-for and iterator-for [duplicate]
can someone tell me if using the range-for is different from using the iterator-for
//I use Array bfor instance, I mean any Iterable container
std::vector<myClass> v;
for(auto&& e : v){
//do stuff
//maybe remove
}
//compared with
for(auto it = v.begin(); it!= v.end; ++it){
//do stuff
//maybe remove
}
Are there anomalies in insertion or deletion from the array in the first version compared with the second
Solution 1:[1]
can someone tell me if using the range-for is different from using the iterator-for
The range-for is syntactic sugar and can be written using an equivalent traditional for loop with iterators. So, an iterator-for can behave the same as a range-for.
An iterator-for can be different from a range-for if you write it to do something other than what a range-for would do.
For the cases where range-for does what is needed - which is most cases - it is preferred due to its simplicity. It's easy to understand and to write correctly.
Are there anomalies in insertion or deletion from the array
It isn't possible to insert or delete elements of an array. I suppose that you meant vector.
You must not do operations on vector that you are iterating that would invalidate the current iterator in a range-for loop. Insertion and erasure will invalidate iterators in many cases.
An iterator loop can sometimes be written in a way that isn't identical to a range-for where the invalidation of the iterator is not a problem.
That said, you typically shouldn't use either for "maybe remove". You should probably be using the remove-erase idiom.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
