简体   繁体   中英

Is there a reason to use std::distance() over iterator::operator-()?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM