C ++如何在迭代时从向量中擦除 [英] C++ how to erase from vector while iterating
问题描述
std::vector<int *>intList;
int *a = new int;
*a = 3;
int *b = new int;
*b = 2;
int *c = new int;
*c = 1;
intList.push_back(a);
intList.push_back(b);
intList.push_back(c);
std::vector<int *>::iterator it;
for (it = intList.begin(); it != intList.end();)
{
int *a = (int*)*it;
if ((*a) == 2)
{
delete a;
intList.erase(it);
}
else
{
++it;
}
}
当从向量中删除某些内容时,此代码在for循环的开头崩溃.我不明白为什么.如果有帮助,我正在使用Visual Studio 2015
This code crashes at the start of the for loop when something is erased from the vector. I do not understand why. I am using Visual Studio 2015 if that helps
推荐答案
erase
返回下一个迭代器.
if ((*a) == 2)
{
delete a;
it = intList.erase(it);
}
remove()
和 remove_if()
将复制元素(此处为指针),最后将指向多个指向相同整数的元素,如果您尝试释放它们,您将剩下悬空的指针.
remove()
and remove_if()
will copy the elements(pointer here) and one will end up with multiple elements pointing to same integer and if you then try to free them, you'll be left with dangling pointers.
考虑矢量有 4
个看起来像
0x196c160 0x196bec0 0x196c180 0x196bee0
可能会想使用 erase-remove
习惯用法
auto temp = remove_if(vec.begin(),vec.end(),[](const auto &i){return *i==2;});
现在看起来像
0x144aec0 0x144b180 0x144b180 0x144aee0
temp
将指向 3rd
元素和一个
for(auto it=temp;it!=vec.end();it++)
delete *it;
现在第二个元素是一个悬空指针.
Now the second element is a dangling pointer.
如果您在复制元素之前删除
,可以解决上述问题.请查看@Dietmar的答案.
EDIT 2:
The above problem could be solved if you delete
before the element is copied.Look at @Dietmar's answer.
这篇关于C ++如何在迭代时从向量中擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!