1

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.

Krakkos
  • 1,439
  • 3
  • 19
  • 24

3 Answers3

7

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

3

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
  • 58,213
  • 10
  • 98
  • 113
  • as the vector is global, can I compare the myObt pointer to myObjectVecor.end(); – Krakkos Mar 16 '09 at 12:50
  • I'm not sure if this is truly safe or not... for this to work, "&vec.back()" or "&*vec.end()" would be required to be an object beyond the end of the contiguous space which I do not believe is a guarantee in the Standard. – D.Shawley Mar 17 '09 at 13:26
2

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
  • 167,383
  • 100
  • 513
  • 979
  • 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 Mar 16 '09 at 12:55
  • At least you can do this with VC++ implementation. – sharptooth Mar 16 '09 at 12:59
  • pObj == vec.end() is only valid if the vector iterator is just a typedef T* which is not guaranteed. vector doesn't provide direct access to it's internal pointer and you can't deref vec.end() so the only time you can check a raw pointer against end (&vec[0] + vec.size()) is when vec.size() >= 1. – Functastic Mar 16 '09 at 14:00