+ 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
1 Resposta
+ 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.