views:

509

answers:

4

I have a vector of myObjects in global scope.

std::vector<myObject>

A method is passed a pointer to one of the elements in the vector. Can this method increment the pointer, to get to the next element,

myObject* pmObj;

++pmObj; // the next element ??

or should it be passed an std::Vector<myObject>::iterator and increment that instead?

Assume for now that the vector will not get changed in the meantime.

+5  A: 

Yes - the standard guarantees in a technical correction that the storage for a vector is contiguous, so incrementing pointers into a vector will work.

anon
Except for std::vector<bool>!
David Holm
orly? how come?
Krakkos
therefromhere
+2  A: 

If the vector is not reallocated and you're sure not to get out of vector's bounds then you can use this approach. Incrementing pointers is legal and while you have space to move to the next element you can do so by incrementing the pointer since the vector's buffer is a single block of memory.

sharptooth
yes, the vecotr won't be reallocated, but eventually I could reach the vectors bounds... can I check for pmyObj == myObjectVector.end() before using it?
Krakkos
At least you can do this with VC++ implementation.
sharptooth
Functastic
+3  A: 

Yes, this will work as expected since std::vector is mandated to use contiguous storage by the Standard. I would suggest passing in a pair of iterators if you are working with a range of objects. This is pretty much the standard idiom as employed by the STL. This will make your code a little safer as well since you have an explicit endpoint for iteration instead of relying on a count or something like that.

D.Shawley
as the vector is global, can I compare the myObt pointer to myObjectVecor.end();
Krakkos
D.Shawley
+1  A: 

A related question.

Ferruccio