5

A problem in C++ primer, when begin and end work on vector I know there is vector::size() could help, but how do they work when I just give an array argument. just like:

int arr[] = {1, 2, 3};
size = end(arr) - begin(arr);

how do end(arr) and begin(arr) work correctly ?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
alexxx
  • 135
  • 1
  • 7

2 Answers2

4

So to see how std::end works we can look at How does std::end know the end of an array? and see that the signature for std::end is:

template< class T, std::size_t N >
T* end( T (&array)[N] );

and it is using template non-type parameter to deduce the size of the array and it is just a matter of pointer arithmetic to obtain the end:

return array + N ;

For std::begin the signature is identical, with the exception of the name:

template< class T, std::size_t N >
T* begin( T (&array)[N] );

and calculating the beginning of the array is simply a matter of array to pointer decay which gives us a pointer to the first element of the array.

In C++14 these both become constexpr.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
2

I'll just paste a piece of code from here

template <class _Tp, size_t _Np>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
_Tp*
begin(_Tp (&__array)[_Np])
{
    return __array;
}

template <class _Tp, size_t _Np>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
_Tp*
end(_Tp (&__array)[_Np])
{
    return __array + _Np;
}
Xiaotian Pei
  • 3,210
  • 21
  • 40