Vector iterators incompatible error for a vector holding iterators of another vector

Vector iterators incompatible error for a vector holding iterators of another vector

参考这个 ,我纠正了我的错误并将迭代器更改为相同的 "vector type" 即

我替换了行

auto startIter = table.begin();

auto startIter = tabTypeIterVector[0];

在 AccessTableIteratorsVector() 函数的 for 循环中。 然而,在下面的代码中,我仍然收到“调试断言失败,向量迭代器不兼容错误, 当在 for 循环中命中此行时

itloop !=-endIter

typedef vector<vector<string> tableDataType;
vector<tableDataType::Iterator> tabTypeIterVector;
tableDataType table;
FillRows(vector<string> vstr)
{
    table.push_back(vstr);
    if(some_condition_satisfied_for_this_row())
    {
        tableDataType::Iterator rowIT = table.end();
        tabTypeIterVector.push_back(rowIT);
    }
}


In another function:

AccessTableIteratorsVector()
{
auto startIter =  tabTypeIterVector[0];
auto endIter = tabTypeIterVector[1];
   for(auto itloop=startIter; itloop !=-endIter;itloop++)
   {

   }
}

push_back might cause a reallocation of the data contained in the vector. And that reallocation will make all iterators to the vector invalid. Dereferencing invalid iterators leads to undefined behavior.

向量中的索引将继续有效,除非您从向量中删除元素。