简体   繁体   English

是否有理由在 iterator::operator-() 上使用 std::distance() ?

[英]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.我不确定为什么有std::distance(iterator const&, iterator const&)iterator::operator-(iterator const&) (以及适配器operator-(iterator const&, iterator const&) ),其中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. operator -不是大多数迭代器类型的成员,因此除非您的算法仅支持随机访问,否则一般使用它是错误的。

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.另一方面, std::distance知道迭代器类别,并将使用operator -如果可用,如果不可用,它将使用N调用operator --进行减法。

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)).对于某些人来说,将违反的性能约束放在一边甚至没有意义(它应该是 O(1),而不是 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. std::distance()因此回退到迭代,直到距离被覆盖作为回退,这是一个基本的迭代器操作。

That degradation is not always acceptable though, and if it happens the distance better be positive, on pain of UB.然而,这种退化并不总是可以接受的,如果发生这种情况,距离最好是积极的,因为 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.写入接口(您需要的最小接口),而不是实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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