Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c++ - Vector iterators incompatible error for a vector holding iterators of another vector

With reference to this previous SO question , I corrected my mistake & changed the iterators to be of same "vector type" i.e.

I replaced the line

auto startIter = table.begin();

with

auto startIter = tabTypeIterVector[0];

in the for loop in AccessTableIteratorsVector() function. wrt below code, however, I'm still getting the "Debug assertion failed, vector iterators incompatible error, when this line is hit in for loop

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++)
   {

   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Indexes into the vector will continue to stay valid, unless you remove elements from the vector.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...