One of the common cases when you need the difference between iterators is a binary search: without knowing the distance, you do not know how much you need to add to the iterator on the left side to get to the middle in O(1) time. Once you know the distance, you can apply the mixed arithmetic of an iterator-scalar to get to the middle, also in constant time.
Note that you can find the distance by repeating the increment of one iterator until you reach another, but it will take O(n) .
You will also need a < b comparison to find out which iterator is on the left side and which is on the right. Without this comparison, you will not be able to verify the input data for your binary search algorithm.
I am confused [that] the subtraction operator should return an int, not an iterator, although βlogicallyβ I would expect that an arithmetic operation between two objects of the same type would also return an object of this type.
Subtraction gives you the distance β the number of steps from one point to another. This is a scalar number that does not depend on the type of iterator. The symmetry here is simple: since
iteratorA + scalar = iteratorB
simple arithmetic rules tell us that
scalar = iteratorB - iteratorA
source share