How do I erase a vector element with a pointer?

I have it:

vector<Object*> myVec;

      

and add my objects to it like this:

Object *obj1 = new Object;
myVec.push_back(obj1);

      

Suppose I have 100 objects this way and the pointers go like * obj1, * obj2 ... * obj100.
And now I want to remove let say, obj37, from the vector. I wish I was able to do this in the same way as pushing it:

myVec.remove_back(obj37);

      

It would be great if there was a function like remove_back, but I don't think so. I hope you understand that you helped me with this.

By the way, just look at the question , in the accepted answer, the algorithm for removing the algorithm works by value:

vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

      

I gave it a chance that with a pointer, even I didn't think it would work and surprise; he didn't:

myVec.erase(std::remove(myVec.begin(), myVec.end(), *obj37), vec.end());

      

Yes, I know I just have shit, but it's important to you. There must be a simple solution like this somewhere, and I just want it.

+3


source to share


3 answers


You're almost there: find an element by value:

myVec.erase(std::remove(myVec.begin(), myVec.end(), obj37), myvec.end());
//                                                  ^^^^^

      

Alternatively, if you know the item is at position 36 (0 based), you can erase it directly:

myvec.erase(myvec.begin() + 36);

      



Or, in modern C ++:

myvec.erase(next(begin(myvec), + 36));

      

Also note that it std::remove

searches the entire vector, so if you know there is only one element, you can use find

instead to stop as soon as you find the value:

{
    auto it = std::find(myVec.begin(), myVec.end(), obj37);
    if (it != myVec.end()) { myVec.erase(it); }
}

      

+5


source


std::remove()

"removes" the values ​​matching the last argument. That is, you can delete the pointer like this:

myVec.erase(std::remove(myVec.begin(), myVec.end(), ptr), myVec.end());

      



If there is only one item, it is easier to use std::find()

instead std::remove()

. If you really want to match the value specified in the value, you must use the version of the _if

algorithm with the appropriate predicate. Of course, deleting the pointer won't free memory.

+1


source


If you are using C ++ 11 you can put smart pointers in your vector. Than you can use the erase method to erase the object and the smart pointer automatically handles the erase pointer stuff.

vector<std::shared_ptr<Object>> myVec;

      

Shared_ptr has a reference router inside. If the object does not refer to any variable, it will be automatically deleted.

0


source







All Articles