0
我在网上搜索很长时间。但没用。请帮助或尝试提供一些想法如何解决这个问题。向量迭代器不可递增,这与迭代器和擦除的操作有关
class Solution{
public:
int removeElement(vector<int> &nums, int val)
{
for (auto &it = nums.begin(); it != nums.end(); ++it)
{
if (*it == val)
{
it = nums.erase(it);
}
}
return nums.size();
}
};
int main(void)
{
Solution s;
vector<int> vi = { 3, 2, 2, 3 };
cout << "size = " << s.removeElement(vi, 3) << endl;
for (auto &i : vi)
{
cout << i << " ";
}
cout << endl;
return 0;
}
哪些是我的代码的类体和主函数体。 但是当我运行它,编译器弹出一个窗口:
这不是显示错误的编译器,这是你的程序*崩溃*。 –
@JoachimPileborg感谢您指出我的错误 –
顺便说一句:http://stackoverflow.com/a/347478/440119 - 它不仅方便,而且比您的方法更具运行效率。 –