Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl::iterators with raw pointers

Tags:

c++

pointers

stl

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?

like image 621
Stefano Piovesan Avatar asked Jul 17 '26 11:07

Stefano Piovesan


2 Answers

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.

like image 113
NathanOliver Avatar answered Jul 19 '26 01:07

NathanOliver


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

It's possible to implement std::begin for a pointer, but it is impossible to implement std::end (because as you say, the size is unknown), so it is a bit pointless.

However, you don't need either of those to use std::find:

int* p = std::find(pStart, pStart + SIZE, 5);
like image 37
eerorika Avatar answered Jul 19 '26 01:07

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!