I currently have a vector of a class Foo and another vector of pointers that point to a subset of the Foo‘s in the vector. I currently have a function that selects some pointers from the vector<Foo *> and deletes them from the vector<Foo> that actually contains them. Thus, at the outset, the two vectors look like this:
//Foo classes in vector<Foo>
a
b
c
d
and
//Foo pointers in vector<Foo *>
*a
*b
*c
*d
However, I discover that after deleting a Foo, say b, they look like this:
//Foo classes in vector<Foo>
a
c
d
and
//Foo pointers in vector<Foo *>
*a
*c
*d
*d
How come the pointer to c in vector<Foo *> doesn’t stay pointed to c after b gets deleted in vector<Foo>? Is there any way to remedy this?
(I understand that if I delete b, the original pointer to b would be a dangling one; however, since I did not intend to access b after its deletion anyway, I thought it wouldn’t matter and I could go to the next index with the pointer to c)
EDIT:
As requested, the code where the pointer vector is filled:
for(int i = 0; i < a.size(); i++) //a is the vector<Foo>
{
Foo * thisFoo = &a[i];
if(someConditionMet)
b.push_back(thisFoo); //b is the vector<Foo *>
}
A
vectorstores its elements in an array. An array is a contiguous sequence of elements.If you have a
vectorcontaining elementsa, b, c, dand remove elementb, then elementscanddare moved down one index in the array to fill the hole created by the removed element, leaving an array containinga, c, d.The pointers don’t “follow” the elements in the
vectoras they are moved. If you have a pointer “toc,” that pointer really points to “the element at index2in the array.” When you removebfrom the array, “the element at index2” is thend, notc.If you want an object to have a fixed address that never changes, you should dynamically allocate it yourself and track it using a smart pointer (like
unique_ptrorshared_ptr).