What’s the recommended way of iterating a container in C++11?
Using
container.begin() and container.end()
Or
begin(container) and end(container)
If any, when is one preferred over the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The better way is
because it’s more extensible. For example, template argument deduction can be used to determine the size of a static array and hence
begin(my_static_array)andend(my_static_array)will work.More generally, you can add overloads/specialisations to begin(.) end(.) and use immutable legacy types in generic algorithms.
You really only need to worry about this if you’re writing a generic algorithm youself
In client code it doesn’t matter so much. In fact, I would say don’t use the new form in that case — I like to reserve certain styles/idioms for certain circumstances, divide my mindsets. But that’s just me.