vector中在删除一个元素后,迭代器会自动指向下一个元素,很可能导致迭代器越界。
《The C++ Standard Library》中解释:
c.erase(pos) | Removes the element at iterator position pos and returns the position of the next element |
所以,正确做法应该是:
vector<int> arr;
arr.push_back(6);
arr.push_back(8);
arr.push_back(3);
arr.push_back(8);
for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )
{
if(* it == 8)
{
it = arr.erase(it);
}
else
{
++it;
}
}