std::begin
and std::end
know the beginning and end of a container
or an array
.
It so easy to know the end
and begin
of a vector
for example because it is a class that gives this information. But, how does it know the end of an array
like the following?
int simple_array[5]{1, 2, 3, 4, 5}; auto beg=std::begin(simple_array); auto en=std::end(simple_array);
std::begin
is not that hard to know where the array start. But how does it know where it ends? Will the constant integer 5
be stored somewhere?
I would appreciate if I got an answer with some low-level information.
The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.
std::array::endReturns an iterator pointing to the past-the-end element in the array container. The past-the-end element is the theoretical element that would follow the last element in the array. It does not point to any element, and thus shall not be dereferenced.
std::array provides fixed array functionality that won't decay when passed into a function. std::array is defined in the <array> header, inside the std namespace. Just like the native implementation of fixed arrays, the length of a std::array must be known at compile time.
But, how does it know the end of an array
It uses a template non-type parameter to deduce the size of the array, which can then be used to produce the end pointer. The C++11 signature from the cppreference section for std::end is as follows:
template< class T, std::size_t N > T* end( T (&array)[N] );
As hvd notes, since it is passed by reference this prevents decay to a pointer.
The implementation would be something similar to:
template< class T, std::size_t N > T* end( T (&array)[N] ) { return array + N ; }
Is the constant integer 5 will be stored some where?
5
or N
is part of the type of the array and so N
is available at compile time. For example applying sizeof to an array will give us the total number of bytes in the array.
Many times we see an array passed by value to a function. In that case, the array decays to a pointer to type stored in the array. So now the size information is lost. Passing by reference allows us to avoid this loss of information and extract the size N
from the type.
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