从向量中删除元素 [英] Erasing elements from a vector
问题描述
我想使用erase方法从向量中清除一个元素。但是这里的问题是元素不能保证在向量中只出现一次。它可能存在多次,我需要清除所有的。我的代码是这样的:
I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:
void erase(std::vector<int>& myNumbers_in, int number_in)
{
std::vector<int>::iterator iter = myNumbers_in.begin();
std::vector<int>::iterator endIter = myNumbers_in.end();
for(; iter != endIter; ++iter)
{
if(*iter == number_in)
{
myNumbers_in.erase(iter);
}
}
}
int main(int argc, char* argv[])
{
std::vector<int> myNmbers;
for(int i = 0; i < 2; ++i)
{
myNmbers.push_back(i);
myNmbers.push_back(i);
}
erase(myNmbers, 1);
return 0;
}
这段代码显然崩溃了,因为我改变了向量的结尾,它。什么是实现这个的最好的方法?也就是说有没有办法做到这一点,没有迭代向量多次或创建一个多个副本的向量?
This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector?
推荐答案
使用删除/清除成语:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
会发生什么? remove
与向量
开始处的要删除的值( number_in
)不同,并将迭代器返回到第一个元素。然后 erase
删除这些元素(未指定值)。
What happens is that remove
compacts the elements that differ from the value to be removed (number_in
) in the beginning of the vector
and returns the iterator to the first element after that range. Then erase
removes these elements (who's value is unspecified).
这篇关于从向量中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!