Erasing elements in a vector

Aug 12, 2010 at 1:34am
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?
Aug 12, 2010 at 2:03am
what do you mean by a reference location?

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.
Aug 12, 2010 at 3:26am
If you need just remove element - object from vector v;

 
v.erase(std::remove(v.begin(), v.end(), object), v.end());


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)
Aug 12, 2010 at 1:57pm
@Disch - I meant a particular element, and not a range

@Denis - That's what I was looking for :)
Aug 12, 2010 at 3:02pm
@Disch - I meant a particular element, and not a range


What I said still stands.

You can use erase to remove a single element.

You cannot remove any elements without invalidating all iterators.
Aug 12, 2010 at 5:56pm
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.

http://cplusplus.com/reference/stl/vector/erase/
This invalidates all iterator and references to elements after position or first.
Aug 12, 2010 at 6:01pm
Ah. Yeah I guess that makes sense.

I suppose pop_back only invalidates the last iterator then, too.
Aug 13, 2010 at 3:42am
I've read this book about STL
http://www.amazon.com/Effective-STL-Specific-Standard-Template/dp/0201749629
It's very interesting, easy to read and usefull in work practice.
Topic archived. No new replies allowed.