[cs13001] cs1b questions

Mikhail Nesterenko mikhail at cs.kent.edu
Mon May 9 11:16:09 EDT 2016


> 1. subtracting 2 pointers (i assume can do the same with iterators too)
> will not really give the number of elements in between but it also* includes
> the end element.*

it is to be expected. That is, if

   ip2 = ip1 + 3;

Then

   cout << ip2 - ip1;  // is 3


> 
> 2. Validity of iterators, would you clarify slide#9, last bullet. point
> CAUTION.


After update operations: erase() and insert() the iterators that are
pointing to the vector on which the update operations are performed
are _invalidated_. This means that the result of accessing these
iterators (for example, by dereferencing) is unspecified. 

This has to do with vector implementation as dynamically allocated
array. When erase() and insert() are executed, the internal dynamic
array may have to be reallocated. This makes the iterator point to
obsolete and incorrect information.

Here is an example:

     vector<int> v(5);
     vector<int>::iterator p;
     p = v.begin()+3; // p points to 4th element
     v.erase(v.begin()); // erasing the first element of the vector
     			 // this invalidates p
     cout << *p; // p is invalidated, result is unspecified
     	         // run-time error


Thanks,
-- 
Mikhail


More information about the cs13001 mailing list