Reputation: 25581
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?
Upvotes: 26
Views: 3688
Reputation: 1
I think the new syntax with range based for loops
for (auto item : container)
is probably the most C++11 like.
As others commented, you sometimes want auto&
or const auto&
instead of auto
.
Upvotes: 37
Reputation: 33385
The better way is
begin(container)
end(container)
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)
and end(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
template <typename T>
void foo (T & t)
{
bar (begin(t), end(t)); // certainly better than bar(t.begin(), t.end())
}
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.
for (auto i = c.begin(); i != c.end(); ++i)
// I can see at-a-glance that c is a STL-style container.
// That might be useful to know. I can probably dismiss static arrays
// and unorthodox containers as possibilities.
foo (i, c.size());
Upvotes: 24