vector的迭代器使用
vector中增删元素后会使得其原有的迭代器失效。因此对vector进行遍历的过程中,如果需要对数组中的元素进行增删,应该避免使用迭代器进行操作。
如果不可避免要使用的话,必须要在增删元素后重新定位迭代器
举例如下:
std::vector<int> inVec = {1,2,3};
for (auto it = inVec.begin(); it != inVec.end(); ++it)
{
std::cout << *it << endl;
if (*it == 3)
{
it = inVec.erase(it);
if (it == inVec.end())
{
break;
}
}
}
-------------------------
std::vector<int> vecRes(4, 100);
for (auto it = vecRes.begin(); it != vecRes.end(); ++it)
{
it = vecRes.insert(vecRes.end(), 10);
cout << *it << endl;
}
--------------------------
_Vector_iterator& operator++()
{
// preincrement
++*(_Mybase *)this;
return (*this);
}