I have a std::vector containing a lot of elements. As the vector is huge, I store pointers to some specific elements in another vector, to be able to access them faster. But as the vector grows, sometimes its internal container gets reallocated, causing all my pointers to become invalid.
Is there a way to know when this happens? This way I can update the pointers in the other list.
You shoudldn’t store pointers, you should store indexes :
i.e, instead of :
and access
*var1,*var2you should store :
and access
vector[i1],vector[i2]Note : you should still be careful if you use modifier methods :
pop_back()(which makes the last position invalid)erase(i)(which shifts all the indexes greater than i)(your first method had the same caveat)