C++学习之路(14)---vector报错:vector iterator not incrementable"或"vector iterator + offset out of range"

测试代码1:
vector g_vtStr1;
vector g_vtStr2;
vector g_vtStr3;
g_vtStr1.push_back(_T(“Test1”));
g_vtStr1.push_back(_T(“Test2”));
g_vtStr1.push_back(_T(“Test3”));
g_vtStr1.push_back(_T(“Test0”));
sort(g_vtStr1.begin(),g_vtStr1.end());

g_vtStr2.push_back(_T("data1"));
g_vtStr2.push_back(_T("data2"));
g_vtStr3.resize(g_vtStr2.size());

//如果g_vtStr3 的 size要小于 g_vtStr1-g_vtStr2的差值 下面会报错奔溃,因此必须保证g_vtStr3 的size大小足够容纳差值
vector::const_iterator it = set_difference(g_vtStr1.begin(),g_vtStr1.end(),g_vtStr2.begin(),g_vtStr2.end(),g_vtStr3.begin());

测试代码2:
for (vector::const_iterator i = g_vtStr1.begin();i != g_vtStr1.end();++i)
{
if ( i->CompareNoCase(_T(“Test0”)) == 0 )
{
i = g_vtStr1.erase(i);//此处会报错
}

}

代码在处理Iterator的earse的时候有点问题。当执行了一次earse操作之后,原来用来遍历的iterator就失效了。同时earse操作会返回一个指向r下一个元素的iterator,如果想继续遍历,就得用返回的iterator继续操作。
改成:
for (vector::const_iterator i = g_vtStr1.begin();i != g_vtStr1.end();)
{
if ( i->CompareNoCase(_T(“Test0”)) == 0 )
{
i = g_vtStr1.erase(i);
}
else
{
++i;
}
}

你可能感兴趣的:(C++)