简体   繁体   English

C++ 中 Vector 的 std::upper_bound 和 std::lower_bound 的复杂度是多少?

[英]What is the complexity for std::upper_bound and std::lower_bound for Vector in C++?

What is the complexity of the std::lower_bound and std::upper_bound functions. std::lower_boundstd::upper_bound函数的复杂度是多少。

I know in case of std::set<int> it is log(n) , but I have no idea for a std::vector<int> .我知道在std::set<int>情况下它是log(n) ,但我不知道std::vector<int>

I was going through an implementation of the Longest Increasing Subsequence using vectors and std::lower_bound .我正在使用向量和std::lower_bound来实现最长std::lower_bound

What is the complexity of this code?这段代码的复杂度是多少?

int LIS2(vector<int> a) {
    vector<int> v;
    for (int i = 0; i < a.size(); i++) {
        auto it = lower_bound(v.begin(), v.end(), a[i]);
        if (it != v.end()) 
            *it = a[i];
        else 
            v.push_back(a[i]);
    }
    return v.size();
}

From https://en.cppreference.com/w/cpp/algorithm/lower_bound :https://en.cppreference.com/w/cpp/algorithm/lower_bound

Complexity复杂

The number of comparisons performed is logarithmic in the distance between first and last (At most log 2 (last - first) + O(1) comparisons).执行的比较次数是第一个和最后一个之间距离的对数(最多log 2 (last - first) + O(1)比较)。 However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.但是,对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的。

For random access iterators (eg from std::vector ) the bounds functions simply do a binary search.对于随机访问迭代器(例如来自std::vector ),边界函数只是进行二分查找。

For non-random access iterators (eg from std::list and std::set ) the functions still perform a binary search but there is an additional cost as they have to increment the iterators one element at a time to move between elements.对于非随机访问迭代器(例如来自std::liststd::set ),函数仍然执行二分搜索,但有额外的成本,因为它们必须一次增加一个元素以在元素之间移动。

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

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