[cs13001] Final exam Inquiry - Kevin Zita - csi

Mikhail Nesterenko mikhail at cs.kent.edu
Sun May 4 19:49:47 EDT 2014


> I'm currently reviewing for the final exam and I'm curious if this would
> work to add and delete an element from a vector using iterators.
> 
> 
> for(vector<int>::iterator exampleIter = v.begin();
> exampleIter != v.end();
> ++exampleIter){
> 
> 
>     if(*exampleIter == 3) {
>         v.erase(exampleIter);
>         v.insert(exampleIter, 2);
>     }

erase() _invalidates_ iterator exampleIter. That is, after erase(),
the value of exampleIter is undefined and result of following insert()
is unspecified. The reason is that internally vector is implemented as
dynamically allocated array so erasing causes memory
reallocation. Therefore, the above code does not work.

However, erase() returns an iterator to the next element after the
removed. Hence, there is this iterate-and-erase idiom.  Can you figure
out how it works and why it avoids using invalidated iterator?

    for(vector<int>::iterator exampleIter=v.begin();
    	exampleIter != v.end();
	)
	
	if(/* must delete element condition */)
	     exampleIter = v.erase(exampleIter);
	else
	     ++exampleIter;		      

Thanks,
--
Mikhail


More information about the cs13001 mailing list