为什么std :: binary_search使用ForwardIterator而不是RandomIterator?

时间:2015-09-06 05:55:02

标签: c++ stl iterator

我很惊讶它在使用不支持?cbrt的ForwardIterator时如何计算middle

2 个答案:

答案 0 :(得分:1)

对于cource,您可以计算元素的数量,即使它不是随机迭代器。

如果它是一个随机迭代器,你只需last - first即可在一个恒定时间内得到它,至少你可以逐个推进first直到last ,并以线性复杂度计算。

应该实现的是根据迭代器标记来调度它,这里是std::advance的实现图像的一个示例,显示了如何根据迭代器的类型进行调度: / p>

template <class InputIterator, class Distance>
inline void __advance(InputIterator& i, Distance n,
input_iterator_tag)
{
    while (n--) ++i;
}
template <class ForwardIterator, class Distance>
inline void __advance(ForwardIterator& i, Distance n,
forward_iterator_tag)
{
    advance(i, n, input_iterator_tag());
}
template <class BidiectionalIterator, class Distance>
inline void __advance(BidiectionalIterator& i, Distance n,
bidirectional_iterator_tag)
{
    if (n >= 0)
        while (n--) ++i;
    else
        while (n++) --i;
}
template <class RandomAccessIterator, class Distance>
inline void __advance(RandomAccessIterator& i, Distance n,
random_access_iterator_tag)
{
    i += n;
}
template <class InputIterator, class Distance>
inline void advance(InputIterator& i, Distance n)
{
    __advance(i, n, iterator_traits<InputIterator>::iterator_category());
}

答案 1 :(得分:1)

R> install.packages("codetools", lib = "/usr/lib/R/library") trying URL 'https://cran.rstudio.com/src/contrib/codetools_0.2-14.tar.gz' Content type 'application/x-gzip' length 12938 bytes (12 KB) ================================================== downloaded 12 KB * installing *source* package ‘codetools’ ... ** package ‘codetools’ successfully unpacked and MD5 sums checked mv: cannot move ‘/usr/lib/R/library/codetools’ to ‘/usr/lib/R/library/00LOCK-codetools/codetools’: Permission denied Warning in file.copy(f, instdir, TRUE) : problem copying ./NAMESPACE to /usr/lib/R/library/codetools/NAMESPACE: Permission denied Warning in file(file, ifelse(append, "a", "w")) : cannot open file '/usr/lib/R/library/codetools/DESCRIPTION': Permission denied Error in file(file, ifelse(append, "a", "w")) : cannot open the connection ERROR: installing package DESCRIPTION failed for package ‘codetools’ * removing ‘/usr/lib/R/library/codetools’ Warning in install.packages : installation of package ‘codetools’ had non-zero exit status The downloaded source packages are in ‘/tmp/RtmpiJWb8L/downloaded_packages’ Updating HTML index of packages in '.Library' Warning in install.packages : cannot create file '/usr/share/R/doc/html/packages.html', reason 'Permission denied' Warning in install.packages : cannot update HTML package index 的行为在理论上等效(对于非比较器版本)

std::binary_search()

其中template <class ForwardIterator, class T> bool binary_search (ForwardIterator first, ForwardIterator last, const T& val) { first = std::lower_bound(first,last,val); return (first!=last && !(val<*first)); } 可以根据需要专门用于不同的迭代器(例如,对std::lower_bound()使用std::distance()std::advance(),对于不同的迭代器使用其他技术(如果适用于实现)。请记住,ForwardIteratorBidirectional迭代器是RandomAccess的特化。