user3444650 user3444650 - 7 months ago 71
C++ Question

Preventing pointer invalidation when using pop_back

If there's a pointer pointing to the last element of a vector, and I want to remove the element but keep the data via a pointer, how can I do it?

vector<int> a;
int * b = a[0];
a.pop_back; //b is invalidated

Am I forced to use a different container or is there another way?


From the question it seems you specifically want to keep a pointer an element which is removed from the container. All containers invalidate pointers and references to erased objects. If you need to erase an objects from a container but keep the pointed to object alive, the only standard library container viable is a std::list<T>: you can splice() the object into a different list:

std::list<int> a;
std::list<int> removed;

int* b = &a.front();
a.splice(a.begin(), removed);

After this operation the object pointed to by b isn't in a but it is in removed instead.