Why use non-member begin and end functions in C++11?

Jonathan M Davis picture Jonathan M Davis · Sep 29, 2011 · Viewed 28.6k times · Source

Every standard container has a begin and end method for returning iterators for that container. However, C++11 has apparently introduced free functions called std::begin and std::end which call the begin and end member functions. So, instead of writing

auto i = v.begin();
auto e = v.end();

you'd write

auto i = std::begin(v);
auto e = std::end(v);

In his talk, Writing Modern C++, Herb Sutter says that you should always use the free functions now when you want the begin or end iterator for a container. However, he does not go into detail as to why you would want to. Looking at the code, it saves you all of one character. So, as far as the standard containers go, the free functions seem to be completely useless. Herb Sutter indicated that there were benefits for non-standard containers, but again, he didn't go into detail.

So, the question is what exactly do the free function versions of std::begin and std::end do beyond calling their corresponding member function versions, and why would you want to use them?

Answer

Matthieu M. picture Matthieu M. · Sep 29, 2011

How do you call .begin() and .end() on a C-array ?

Free-functions allow for more generic programming because they can be added afterwards, on a data-structure you cannot alter.