在使用Vector中,如果使用erase不小心,很容易陷入无限循环.如下:
//向数组中添加一个元素
MyArray.push_back(8);
vector<unsigned short>::iterator it = MyArray.begin();
for (;it != MyArray.end();it++)
{
if (*it == 8)
{
MyArray.erase(it); //删除数组中的元素
}
}
注意:在声明
protected:
vector<unsigned short> MyArray;
的头文件中要加入
#include<vector>
using namespace std;
本意是要遍历向量,找到是8的元素,将其删除。但是,上面代码却陷入了无限循环。原因是向量的erase会返回下一个元素的位置,这样的话,会让it加两次,从而跳过了it != MyArray.end().
所以应该将上述代码修改为:
MyArray.push_back(8);
vector<unsigned short>::iterator it = MyArray.begin();
for (;it != MyArray.end();)
{
if (*it == 8)
{
MyArray.erase(it); //删除数组中的元素
}
else
it++;
}