Std :: begin and std :: end do not work with pointers and why?
Why does std :: begin () and std :: end () work with an array, but not with a pointer [almost an array] and an array reference [which is an alias of the original array].
After scratching my head for 15 minutes, I can't get anything on Google.
Below only the first case works, not the second and third, what could be the reason for this?
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
int first[] = { 5, 10, 15 }; // Fist Case
if (std::find(std::begin(first), std::end(first), 5) != std::end(first)) {
std::cout << "found a 5 in array a!\n";
}
int *second = new int[3]; // Second Case
second[0] = 5;
second[1] = 10;
second[2] = 15;
if (std::find(std::begin(second), std::end(second), 5) != std::end(second)) {
std::cout << "found a 5 in array a!\n";
}
int *const&refOfFirst = first; // Third Case
if (std::find(std::begin(refOfFirst), std::end(refOfFirst), 5) != std::end(refOfFirst)) {
std::cout << "found a 5 in array a!\n";
}
}
Mistake:
error: no matching function for call to ‘begin(int&)’
if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) {
^
source to share
Given only a pointer to the beginning of the array, there is no way to determine the size of the array; therefore begin
, end
they cannot work with pointers to dynamic arrays.
Use std::vector
if you want the dynamic array to know its size. As a bonus, this will fix the memory leak as well.
The third case fails because, again, you are using a (reference to) pointer. You can use a reference to the array itself:
int (&refOfFirst)[3] = first;
or, to not specify the size of the array:
auto & refOfFirst = first;
and begin
u end
will work exactly the way they work for first
.
source to share