简体   繁体   English

std::lower_bound 和 std::upper_bound [on hold] 的时间复杂度

[英]Time complexity of std::lower_bound and std::upper_bound [on hold]

I use std::upper_bound on a sorted vector, and it's clearly not working in logarithmic time, as I compare it with my own implementation of upper bound search.我在排序向量上使用std::upper_bound ,它显然不能在对数时间内工作,因为我将它与我自己的上限搜索实现进行了比较。 Why is it happening?为什么会这样? My code:我的代码:

for (size_t i = 1; i < sorted_vector.size(); ++i) {
    size_t m = std::upper_bound(
        sorted_vector.begin(),
        sorted_vector.begin() + i,
        values_to_search[i]) - sorted_vector.begin();

Total time here supposed to be O(n * log(n)) .这里的总时间应该是O(n * log(n)) When I use my own implementation of upper_bound on an array of size 50000 it takes about 0.05 seconds, while with std it's around 3 seconds.当我在大小为 50000 的数组上使用自己的upper_bound实现时,大约需要0.05秒,而使用std大约需要3秒。

Likely, your sorted_vector 's iterator is not a RandomAccessIterator like with std::vector .很可能,您的sorted_vector的迭代器不是像std::vector那样的RandomAccessIterator

Instead you may be dealing with a forward or bidirectional iterator, which would mean O(N) for “jumping” distances across the container in binary search rather than O(1) (which you've indicated you're expecting).相反,您可能正在处理前向双向迭代器,这意味着 O(N) 用于在二分搜索中跨容器“跳跃”距离,而不是 O(1)(您已表示您期望)。

Check to make sure sorted_vector is a std::vector or similar!检查以确保sorted_vectorstd::vector或类似的!

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

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