简体   繁体   English

排序向量上std :: lower_bound的时间复杂度

[英]Time complexity of std::lower_bound on a sorted vector

I was studying std::upper_bound from http://www.cplusplus.com/reference/algorithm/upper_bound/ and I came across the fact that this might run in linear time on non-random access iterators. 我正在从http://www.cplusplus.com/reference/algorithm/upper_bound/学习std::upper_bound ,我发现这可能在非随机访问迭代器上以线性时间运行。

I need to use this for a sorted vector. 我需要将它用于有序矢量。 Now I don't know what are non-random access iterators and whether this will run in logarithmic time on the sorted vector. 现在我不知道什么是非随机访问迭代器以及它是否将在对数时间上运行在已排序的向量上。

Can anyone clear this for me. 任何人都可以为我清除这一点。

§ 23.3.6.1 [vector.overview]/p1: §23.3.6.1[vector.overview] / p1:

A vector is a sequence container that supports random access iterators. 向量是一个支持随机访问迭代器的序列容器。

A random access iterator is the one that is able to compute the offset of an arbitrary element in a constant time, without a need to iterate from one place to another (what would result in linear complexity). 随机访问迭代器是能够在恒定时间内计算任意元素的偏移量而不需要从一个地方迭代到另一个地方(这将导致线性复杂性)的迭代器。

std::lower_bound itself provides generic implementation of the binary search algorithm, that doesn't care much about what iterator is used to indicate ranges (it only requires the iterator to be of at least a forward category). std::lower_bound本身提供了二进制搜索算法的通用实现,它并不关心迭代器用于指示范围(它只需要迭代器至少是一个前向类别)。 It uses helper functions like std::advance to iteratively limit the ranges in its binary search. 它使用诸如std::advance类的辅助函数来迭代地限制其二进制搜索中的范围。 With std::vector<T>::iterator which is of a random access category, std::lower_bound runs with logarithmic time complexity with regards to the number of steps required to iterate over elements, as it can partition the range by half in each step in a constant time. std::vector<T>::iterator一个随机接入类别的, std::lower_bound与对数时间复杂运行具有问候的遍历的元件,因为它可以通过在半分割的范围内所需的步骤数恒定时间内的每一步。

§ 25.4.3 [alg.binary.search]/p1: §25.4.3[alg.binary.search] / p1:

All of the algorithms in this section are versions of binary search and assume that the sequence being searched is partitioned with respect to an expression formed by binding the search key to an argument of the implied or explicit comparison function. 本节中的所有算法都是二进制搜索的版本,并假设被搜索的序列是通过将搜索关键字绑定到隐含或显式比较函数的参数而形成的表达式进行分区的。 They work on non-random access iterators minimizing the number of comparisons, which will be logarithmic for all types of iterators. 它们处理非随机访问迭代器,最大限度地减少了比较次数,这对于所有类型的迭代器都是对数的。 They are especially appropriate for random access iterators, because these algorithms do a logarithmic number of steps through the data structure. 它们特别适用于随机访问迭代器,因为这些算法在数据结构中执行对数步骤。 For non-random access iterators they execute a linear number of steps. 对于非随机访问迭代器,它们执行线性步数。

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

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