Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top