Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...