简体   繁体   English

按值从向量中删除元素 - C++

[英]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您可以对 std::vector 使用 Erase-remove 成语

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 :根据 Kiril 的回答,您可以在代码中使用此功能:

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> .如果出现是唯一的,那么您应该使用std::set<T> ,而不是std::vector<T>

This has the added benefit of an erase member function, which does what you want.这具有erase成员函数的额外好处,它可以满足您的需求。

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从 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.什么都不会发生,向量保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM