How does C ++ start and end when the argument is an array?

The problem is in the C ++ primer, when we start and finish working on a vector, I know that vector vector :: size () can help, but how they work when I just give an array argument. as:

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

how to make end (arr) and start (arr) correctly?

+5
source share
2 answers

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

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

and it uses a non-type template parameter to infer the size of the array, and it's just a matter of pointer arithmetic to get the end:

 return array + N ; 

For std::begin signature is identical except for the name:

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

and calculating the beginning of an array is just a matter of array to evade the pointer , which gives us a pointer to the first element of the array.

In C ++ 14, both of them become constexpr.

+4
source

I will just insert the code snippet 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; } 
+2
source

Source: https://habr.com/ru/post/1235502/


All Articles