Hi, I have been learning stuff about STL and currently learning to insert, mostly in vectors, but in general in sequential containers. In the past when using begin(), i done vector.begin(), but now that I am going over the insert function, the video i am watching the person does begin(vector) , this is also the same for end().
Ive tried both of these ways and they both work. Is there a difference with these, when i look it up I do see different code using the two different way. So does it matter what I use?
The reason why std::begin exists as a free function is that it allows for slightly more generic code in templates. T.begin() only works if begin() is a member function of the type T (vector, map, list, etc.), but begin(T) also works on objects that don't have member functions, like plain arrays (keskiverto already mentioned this, I just wanted to expand on it a bit).
Oh ok I believe I understand now. so if i use vector.begin() I am calling the vectors member function, but using begin(vector) it is using the generic begin() function from the stl?
The typical use of begin() and end() in very generic code would support both standard library versions std::begin() and std::end() as well as user-defined overloads of begin() and end() which are selected via argument-dependent lookup.
1 2 3 4 5 6 7
template < typename SEQUENCE >
void foo( SEQUENCE& seq )
{
using std::begin ;
auto iter = begin(seq) ; // either a begin found via adl or std::begin
// etc.
}
The [] is mere alias syntax for pointer and pointer is not an array. Nevertheless, it is good to emphasize that the default method to pass raw array to function does not "pass the array".