Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to vector at index Vs iterator

I have a vector< Object > myvec which I use in my code to hold a list of objects in memory. I keep a pointer to the current object in that vector in the "normal" C fashion by using

Object* pObj = &myvec[index];

This all works fine if... myvec doesn't grow big enough that it is moved around during a push_back at which time pObj becomes invalid - vectors guarantee data is sequential, hence they make no effort to keep the vector at the same memory location.

I can reserve enough space for myvec to prevent this, but I dnt' like that solution.

I could keep the index of the selected myvec position and when I need to use it just access it directly, but it's a costly modification to my code.

I'm wondering if iterators keep the their references intact as a vector is reallocated/moved and if so can I just replace

Object* pObj = &myvec[index];

by something like

vector<Object>::iterator = myvec.begin()+index;

What are the implication of this?

Is this doable?

What is the standard pattern to save pointers to vector positions?

Cheers

like image 795
André Moreira Avatar asked Jan 23 '26 07:01

André Moreira


1 Answers

No... using an iterator you would have the same exact problem. If a vector reallocation is performed then all iterators are invalidated and using them is Undefined Behavior.

The only solution that is reallocation-resistant with an std::vector is using the integer index.

Using for example std::list things are different, but also the are different efficiency compromises, so it really depends on what you need to do.

Another option would be to create your own "smart index" class, that stores a reference to the vector and the index. This way you could keep just passing around one "pointer" (and you could implement pointer semantic for it) but the code wouldn't suffer from reallocation risks.

like image 69
6502 Avatar answered Jan 24 '26 21:01

6502



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!