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 ?
C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.
Explanation: The statement 'C' is correct. When we pass an array as a funtion argument, the base address of the array will be passed.
Passing Array to Function in C/C++ Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With