I know that erase() will invalidate all iterators in a vector. And that, erase-Remove combination is the way to delete a range of elements from a vector.
What if I have to delete just a reference location that I know of? Is it safe to use erase there? If not, what's the best way to delete in a vector?
The only way to remove an element in a vector is with erase(). And as you mentioned that invalidates all iterators. There is no way to remove elements without invalidating iterators.
if you need to do something befor deleting (for example you do a log) you can use the following
1 2 3 4 5 6 7 8 9 10 11 12 13 14
typedef std::vector <ObjectType > ObjectContainer;
for(ObjectContainer::iterator it(v.begin()); it != v.end(); ++it)
{
if (*it == object)
{
log << "Deletting object " << *it << "\n"
//or other actions
//or if your vector keep pointers you can call delete
//delete *it;
it = v.erase(it);
}
}
But you should remember that remove-erase can't be used to delete object from vector of pointers. In this case you need to use smart pointer(for example boost::shared_ptr, or std::shared_ptr if you use features of new C++ standard)
Actually the erase member function does not invalidate all iterators. According to the documentation it invalidates all iterators between pos and end. So all iterators would be invalidated if you erase the very first element.