Are there any general preferences or rules that explain when container specific versions of begin and end should be used instead of free functions std::begin and std::end?
It is my understanding that if the function is a template whereby the container type is a template parameter then std::begin and std::end should be used, i.e.:
template<class T> void do_stuff( const T& t )
{
std::for_each( std::begin(t), std::end(t), /* some stuff */ );
}
What about in other scenarios such as a standard / member function where the type of container is known? Is it still better practice to use std::begin(cont) and std::end(cont) or should the container’s member functions cont.begin() and cont.end() be preferred?
Am I correct in assuming that there is no benefit in performance by calling cont.end() over std::end(cont)?
If you look at, say, the definition of
std::begin:You see that all it does is reference the
begin()anyway. I suppose a decent compiler will make the difference nil, so I guess it comes down to preference. Personally, I’d usecont.begin()andcont.end()just so that I wouldn’t have to explain it to anybody 🙂As Mooing Duck points out, however,
std::beginalso works on arrays:… so there is that to consider. If you are not using arrays, I’d go with my suggestion. However if you are unsure if what is passed is going to be an STL container, or an array of
<T>, thenstd::begin()is the way to go.