I have been studying dynamic allocation and came across this question on StackOverflow:
Deallocating objects stored in a vector?
One of the upvoted answers explain how to manually manage memory when using "Vectors of Pointers to Objects": iterating through the vector calling delete.
My question is about how to delete particular elements of a vector, not the whole vector. In the example program below, I have a vector of object pointers. Imagine that the x variable of these objects are decremented over time... When the x value of an object reaches a number (let's say 3), I wish to delete the object; HOWEVER, I would like to keep the vector SORTABLE by the x values of the objects at all times.
The problem is that when I call delete on the objects whose x values reach 3, the object is deleted but there's still a pointer there pointing to random memory locations, and the size of the vector stays the same as well.
When I loop through the vector printing the x values, the elements that I called delete on are still there but pointing to values like -53408995. How do I get rid of the pointer element of the vector as well as the object?
Calling erase is not an option because in my actual program (not the minimal example below) the vector is continuously SORTED by other factors that change the x-value equivalents. I can't keep track of their index. I would like to delete both the object and the pointer element when I iterate through the vector to check for the x value.
Example:
#include <iostream>
#include <vector>
class A
{
public:
A(int i) { x = i; }
int x;
};
int main()
{
std::vector<A*> Vec;
Vec.push_back(new A{ 5 });
Vec.push_back(new A{ 4 });
Vec.push_back(new A{ 3 });
std::cout << "Size before = " << Vec.size() << std::endl; // 3
for (auto& a : Vec)
{
std::cout << a->x << std::endl;
if (a->x == 3) { delete a; }
}
std::cout << "Size after = " << Vec.size() << std::endl; // Still 3!
for (auto& a : Vec)
{
std::cout << a->x << std::endl; // Prints 5, 4 and a random memory location like -34528374
}
return 0;
}