Why std::begin() and std::end() works with array but not pointer[which is almost array] and reference of array [which is alias of original array].
After scratching my head for 15 min i am not able to get anything in google.
Below only first case works, not 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";
}
}
Error:
error: no matching function for call to ‘begin(int&)’
if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) {
^
As illustrated, a variable (such as number ) directly references a value, whereas a pointer indirectly references a value through the memory address it stores. Referencing a value indirectly via a pointer is called indirection or dereferencing.
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
Given just a pointer to the start of an array, there's no way to determine the size of the array; so begin
and end
can't work on pointers to dynamic arrays.
Use std::vector
if you want a dynamic array that knows its size. As a bonus, that will also fix your memory leak.
The third case fails because, again, you're using (a reference to) a pointer. You can use a reference to the array itself:
int (&refOfFirst)[3] = first;
or, to avoid having to specify the array size:
auto & refOfFirst = first;
and begin
and end
will work on this exactly as they would work on first
itself.
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