It is stated in C++ Primer that
In C++ pointers and arrays are closely intertwined. In particular, as we’ll see, when we use an array, the compiler ordinarily converts the array to a pointer.
I wanted to use iterators for printing an array. The program below works fine but when I try to print arr2 or arr3, if I'm not mistaken, which is of type int *, I get an error (judging that the & operator means reference below).
error: no matching function for call to ‘begin(int*&)’
int main(int argc, char** argv) {
int arr[] = {0,1,2,3,4,5,6,7,8,9};
auto arr2 = arr;
auto arr3(arr); // I think arr2 and arr3 are of same type
for(auto it = std::begin(arr) ; it != std::end(arr) ; ++it)
std::cout << *it << " ";
std::cout << std::endl;
return 0;
}
Considering the statement, if an array is converted into a pointer by the compiler, how does this program work for printing contents of arr using std::begin() and std::end() and do not work for arr2 or arr3 if all of them are pointers to integers?
Edit
I'm sorry if I couldn't make it clear. I hope I'll clarify the problem by this edit.
Now that I am aware that begin() and end() won't work with pointers (thanks to the answers), I wonder if the quoted text is not true as it specifies that there is an Array -> Pointer conversion. If what text says is true then the type of arr should be a pointer. Is there a problem with the quoted text at this point?
Also, is there any way that I can use begin() and end() for pointers (not STL containers) with specifying the size, possibly using the following constructor?
template< class T, size_t N >
T* begin( T (&array)[N] );
begin()/end()on pointers: You can't, but you can use the pointer itself as range start and pointer + size as end. Example:std::sort(yourPointer, yourPointer + arraySize)