I am unsure why there is both std::distance(iterator const&, iterator const&)
and a iterator::operator-(iterator const&)
(as well as adaptors operator-(iterator const&, iterator const&)
), where iterator
is a placeholder for any iterator. Should one be used over the other, and if so, what circumstances?
CodePudding user response:
operator -
is not a member of most iterator types, so it is an error to use it generically unless your algorithm only supports random access.
std::distance
on the other hand knows about iterator categories and will use operator -
if it is available and if not, it will use N
calls to operator --
to do the subtraction.
CodePudding user response:
Well, subtracting two iterators is not supported by all iterators. For some, it doesn't even make sense, putting aside the violated performance constraints (it should be O(1), not O(n)). And even if it is, why do you think the iterator is a class-type?
std::distance()
thus falls back to iterating until the distance is covered as a fallback, which is a basic iterator-operation.
That degradation is not always acceptable though, and if it happens the distance better be positive, on pain of UB.
Still, especially when writing generic code (or code which might be generalized later), staying generic is good:
Write to the interface (the minimal one you need), not the implementation.