std::begin()

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?
std::begin did appear with C++11. You can call it on plain array too.
See: https://en.cppreference.com/w/cpp/iterator/begin

Essentially, for vector, the std::begin is probably a simple wrapper, like:
1
2
3
begin( vector& v ) {
  return v.begin();
}
Right, it's both the same thing for a vector.

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?
stackoverflow wrote:
The implementation of std::begin() for vectors simply calls std::vector<T>::begin(), so there is no difference between the two in this exact case.

Where std::begin() comes into its own is in generic algorithms (example snippet follows):

https://stackoverflow.com/questions/26290316/difference-between-vectorbegin-and-stdbegin

See also: https://en.cppreference.com/w/cpp/iterator/begin
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.
}
You can call it on plain array too.


If the compiler knows the size of the array. It doesn't work in say a function where the array is passed as [] or as a pointer.
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".
For info, there's also std::size() as well - and since c++20, std::ssize() (signed size)

See https://en.cppreference.com/w/cpp/iterator/size
Topic archived. No new replies allowed.