我正在尝试从特定索引处的 vector 中删除一个对象。 vector 迭代器在整个程序中跟踪索引。在下面的代码中,第一个 IF 语句完美运行。但是,如果迭代器指向最后一个元素以外的任何地方,我会从 vector 中删除该元素,然后递增迭代器。程序崩溃并提示“迭代器不可递增”。
我运行了几次调试器,一切看起来都是正确的,所以我看不出我遗漏了什么?
vector<Card> myVector; //container to hold collection of cards.
vector<Card>::iterator myVectorIterator; //points to each "card" in the collection.
Card Collection::remove()
{
if (myVectorIterator== myVector.end()-1) { //at the last card
//erase the "current" card
myVector.erase(myVectorIterator);
//update to the first card.
myVectorIterator= myVector.begin();
}
else
{
myVector.erase(myVectorIterator);
//crashes here!
myVectorIterator++;
}
return *myVectorIterator;
最佳答案
erase
使迭代器无效,因此以后不能使用它。但它有助于将迭代器返回到删除元素之后的元素:
myVectorIterator = myVector.erase(myVectorIterator);
关于c++ - 如何从 vector 中删除元素并更新迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24739599/