Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 572
Sam Avatar asked Oct 03 '11 07:10

Sam


1 Answers

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;
    }
}
like image 109
Kiril Kirov Avatar answered Oct 23 '22 18:10

Kiril Kirov