+ 1

How to choose what for cycle using?C++

We have some way to access to the container data and the position number using for cycle in C++. They all enough simple but how to choose? Is any of that faster or more thread/exception/etc safe? What are you using in general? Is there another way not included?(except using while(){},do{}while())?? https://code.sololearn.com/cXLW7FaORws7/?ref=app

14th Sep 2020, 2:42 PM
Chicherin Alexey
Chicherin Alexey - avatar
1 Answer
+ 4
If all you want to do is to iterate through a container and get elements, range-based for loop should be the shortest way to do it. In some cases, it may not be feasible - especially when you need the current index number to be used as a position indicator somewhere else. You generally do not want to declare another variable just to serve as a counter, it defeats the purpose of a range-based for loop imo. In the case where you need that, I personally would just opt for array indices (#1). Iterators are a different story. You would prefer them if you foresee yourself reusing that piece of code with a different container, since iterators are more generic and work with most containers. You will also want to use iterators if you plan on adding/removing elements as you iterate through the container.
14th Sep 2020, 4:13 PM
Hatsy Rei
Hatsy Rei - avatar