[cs13001] Lab 12
Mikhail Nesterenko
mikhail at cs.kent.edu
Mon Apr 25 17:18:07 EDT 2016
> I am receiving an error in the remove portion of my code in Lab 12 that says
> "vector iterator not incrementable"
>
> else if (ans == 'r') {
> cin >> num;
> vector<int>::iterator toRemove = v.begin();
> for (vector<int>::iterator ip = toRemove; ip != v.end(); ++ip)
> if (num == *ip) {
> toRemove = ip;
> v.erase(toRemove);
> }
> }
>
After using erase() all iterators pointing to the vector on which the
erase was carried out including, in your case, ip, are
_invalidated_. Meaning that you cannot refer to them or increment
them, as you do in the for-loop. This is because erase() may force
to re-allocate vector's internal structure holding the data.
So, afer erase(), you need to either break out of the loop (easiest for
this lab), or re-initialize all the iterators. This re-initialization
is often done using the proprety of erase() that returns an iterator
to the element following the erased element. Here is an example:
for(auto it=vect.begin(); it != vect.end();)
if (/* need to erase */)
it = vect.erase(it);
else
++it;
Thanks,
--
Mikhail
More information about the cs13001
mailing list