Alex Rivera | Logout

Remove an element from a vector by value - C++

Asked 2011-10-03T07:10:55.550
22

If I have

vector<T> list

Where each element in the list is unique, what's the easiest way of deleting an element provided that I don't know if it's in the list or not? I don't know the index of the element and I don't care if it's not on the list.

Edit
Report

1 Answer

33

You could use the Erase-remove idiom for std::vector

Quote:

std::vector<int> v; 
// fill it up somehow
v.erase(std::remove(v.begin(), v.end(), 99), v.end()); 
// really remove all elements with value 99

Or, if you're sure, that it is unique, just iterate through the vector and erase the found element. Something like:

for( std::vector<T>::iterator iter = v.begin(); iter != v.end(); ++iter )
{
    if( *iter == VALUE )
    {
        v.erase( iter );
        break;
    }
}
answered 2011-10-03T07:14:02.703

Your Answer