开发者

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

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.


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;
    }
}


Based on Kiril's answer, you can use this function in your code :

template<typename T>
inline void remove(vector<T> & v, const T & item)
{
    v.erase(std::remove(v.begin(), v.end(), item), v.end());
}

And use it like this

remove(myVector, anItem);


If occurrences are unique, then you should be using std::set<T>, not std::vector<T>.

This has the added benefit of an erase member function, which does what you want.

See how using the correct container for the job provides you with more expressive tools?

#include <set>
#include <iostream>

int main()
{
   std::set<int> notAList{1,2,3,4,5};

   for (auto el : notAList)
      std::cout << el << ' ';
   std::cout << '\n';

   notAList.erase(4);

   for (auto el : notAList)
      std::cout << el << ' ';
   std::cout << '\n';
}

// 1 2 3 4 5
// 1 2 3 5

Live demo


From c++20

//LIKE YOU MENTIONED EACH ELEMENT IS UNIQUE
std::vector<int> v = { 2,4,6,8,10 };

//C++20 UNIFORM ERASE FUNCTION (REMOVE_ERASE IDIOM IN ONE FUNCTION)
std::erase(v, 8); //REMOVES 8 FROM VECTOR

Now try

std::erase(v, 12);

Nothing will happen, the vector remains intact.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜