Stefano Stefano - 4 years ago 101
C++ Question

stl::iterators with raw pointers

I want to use iterators with C++ arrays, but with raw pointers too.
I can do with a static vector:

#define SIZE 10
int vect[SIZE] = {0};
vect[3] = 5;
int* p = std::find(std::begin(vect), std::end(vect), 5);
bool success = p != std::end(vect);


How can be possible to do it with a raw pointer (maybe a heap allocated vector)?
Of course the compiler does not know the size of the data, so this code

int* pStart = vect;
std::find(std::begin(pStart), std::end(pStart), 5);


gives

error C2784: '_Ty *std::begin(_Ty (&)[_Size])' :
could not deduce template argument for '_Ty (&)[_Size]' from 'int *'


Is it possible to make
begin()
and
end()
aware of it?

Answer Source

No it is not possible to use std::begin and std::end on a pointer. Unlike an array whose size is part of the type and therefor deducible a pointer does not hold the size of the thing it points to. In your case with a pointer you would have to use

std::find(pStart, pStart + SIZE, 5);

The way to avoid this though is to use std::vector when you are not going to know what the szie will be at compile time. It will manage the memory for you and provides begin and end member functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download