按值从向量中删除元素 - C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7631996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove an element from a vector by value - C++
提问by Sam
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.
列表中的每个元素都是唯一的,如果我不知道它是否在列表中,删除元素的最简单方法是什么?我不知道元素的索引,我不在乎它是否不在列表中。
回答by Kiril Kirov
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;
}
}
回答by Lightness Races in Orbit
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
现场演示
回答by 56ka
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);