I was wondering, how is equality (==) established for STL iterators? Is it a simple pointer comparison (and thus based on addresses) or something more fancy?
If I have t
Daniel asked: I was wondering, how is equality (==) established for STL iterators? Is it a simple pointer comparison (and thus based on addresses) or something more fancy?
It depends on implementation. Right now, on Visual C++ 2008, I see the following code (for the list iterator):
bool operator==(const _Myt_iter& _Right) const
{ // test for iterator equality
#if _HAS_ITERATOR_DEBUGGING
_Compat(_Right);
#else
_SCL_SECURE_TRAITS_VALIDATE(this->_Has_container() && this->_Same_container(_Right));
#endif /* _HAS_ITERATOR_DEBUGGING */
return (_Ptr == _Right._Ptr);
}
You'll see above that there is both code for verification of iterator validity, and _Ptr
being a pointer to a list node.
So I guess there is both verification, and simple, raw pointer comparison.
Daniel asked: If I have two iterators from two different list objects and I compare them, will the result always be false?
Until now, it appears the standard was somewhat unclear on the subject. Apparently, they will explicitly write that this kind of operation has undefined results:
Quoting: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#446
The result of using any iterator operation (24.2.1 [input.iterators], 24.2.2 [output.iterators], 24.2.3 [forward.iterators], 24.2.4 [bidirectional.iterators], 24.2.5 [random.access.iterators]) that uses two iterator values as arguments (footnote) which were obtained from two different ranges r1 and r2 (including their past-the-end values) which are not subranges of one common range is undefined, unless explicitly described otherwise.
footnote) Among others these operations are ==, <, binary -, and copy assignment
So I guess it is evil to compare iterator from different containers... ^_^
Daniel asked: What about if I compare a valid value with one that's out of range? Is that always false?
Same as above.