Sunday, March 3, 2013

Be careful with iterators!

OK, I am writing this to give you a strong warning!

STL has much more than you can imagine:

Remember this,

1. vector, deque, they are contiguous

2. list, set they are not.

So the difference is that

1. you can do arithmetic operations with vector deque iterators.

like:  vector<int>::iterator iter; iter=iter+3;

but you cant do this: set<int>::iterator iter; iter=iter-1;

but for both iterators you can do: iter++, iter--; so equivalently you can do copy(set.begin(),set.end(),
ostream_iterator<int>(cout," ")) all this stuff...

2. when you destroy an iterator, something unpredictable will happen...ok predictable.

if it is in category one, all iterators will be destroyed. so like:

deque<int>::iterator iter=myQueue.begin();
myQueue.erase(iter+3);

then iter will also be lost!

However, if it is in category two, you can safely delete one iterator without sabotaging others.

list<int>::iterator iter=myList.begin(), iter2=iter;
iter2++;
myList.erase(iter);
iter=iter2;

...and this is fine.

No comments:

Post a Comment