std::lower_bound 排序向量的时间复杂度
Time complexity of std::lower_bound on a sorted vector
我正在学习 std::upper_bound
来自 http://www.cplusplus.com/reference/algorithm/upper_bound/
我发现这可能 运行 在线性时间内 非随机访问 迭代器。
我需要将其用于排序向量。现在我不知道什么是 非随机访问 迭代器以及这是否会 运行 在排序向量上的对数时间。
谁能帮我解决这个问题。
§ 23.3.6.1 [vector.overview]/p1:
A vector is a sequence container that supports random access iterators.
A random access iterator 能够在恒定时间内计算任意元素的偏移量,而无需从一个地方迭代到另一个地方(这会导致线性复杂度)。
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 类别)。它使用像 std::advance
这样的辅助函数来迭代地限制其二进制搜索中的范围。对于 std::vector<T>::iterator
其中 是 的随机访问类别,std::lower_bound
在迭代元素所需的步骤数方面以对数时间复杂度运行,因为它可以在恒定时间内将范围按每一步划分一半。
§ 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.
我正在学习 std::upper_bound
来自 http://www.cplusplus.com/reference/algorithm/upper_bound/
我发现这可能 运行 在线性时间内 非随机访问 迭代器。
我需要将其用于排序向量。现在我不知道什么是 非随机访问 迭代器以及这是否会 运行 在排序向量上的对数时间。
谁能帮我解决这个问题。
§ 23.3.6.1 [vector.overview]/p1:
A vector is a sequence container that supports random access iterators.
A random access iterator 能够在恒定时间内计算任意元素的偏移量,而无需从一个地方迭代到另一个地方(这会导致线性复杂度)。
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 类别)。它使用像 std::advance
这样的辅助函数来迭代地限制其二进制搜索中的范围。对于 std::vector<T>::iterator
其中 是 的随机访问类别,std::lower_bound
在迭代元素所需的步骤数方面以对数时间复杂度运行,因为它可以在恒定时间内将范围按每一步划分一半。
§ 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.