简体   繁体   English

std::lower_bound 会是 list<> 的对数吗?

[英]Will std::lower_bound be logarithmic for list<>?

Suppose I have a list<int> and maintaining it in ordered state. Can I isert new values into it with logarithmic complexity with code like this假设我有一个list<int>并按顺序维护它 state。我可以使用这样的代码以对数复杂度向其中插入新值吗

#include <iostream>
#include <random>
#include <list>
#include <algorithm>

using namespace std;

ostream& operator<<(ostream& out, const list<int> data) {
    for(auto it=data.begin(); it!=data.end(); ++it) {
        if(it!=data.begin()) {
            out << ", ";
        }
        out << (*it);
    }
    return out;
}

int main() {

    const int max = 100;
    mt19937 gen;
    uniform_int_distribution<int> dist(0, max);
    list<int> data;

    for(int i=0; i<max; ++i) {
        int val = dist(gen);

        auto it = lower_bound(data.begin(), data.end(), val);
        data.insert(it, val);

    }

    cout << data << endl;
}

I would say not, because it is impossible to position iterator in list in O(1) but documentation says strange :我会说不是,因为不可能在O(1) list中使用 position 迭代器,但文档说很奇怪

The number of comparisons performed is logarithmic in the distance between first and last (At most log2(last - first) + O(1) comparisons).执行的比较次数是第一个和最后一个之间距离的对数(最多 log2(last - first) + O(1) 比较)。 However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.但是,对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的。 Notably, std::set and std::multiset iterators are not random access, and so their member functions std::set::lower_bound (resp. std::multiset::lower_bound) should be preferred.值得注意的是,std::set 和 std::multiset 迭代器不是随机访问,因此它们的成员函数 std::set::lower_bound (resp. std::multiset::lower_bound) 应该是首选。

ie it doesn't recomment to use this function for set which is alterady search tree internally.也就是说,它不建议将这个 function 用于set ,它在内部是 alterady 搜索树。 Which containers this function is inteded to use then?那么这个 function 打算使用哪些容器呢? How to insert and maintain sorted then?那么如何插入和维护排序呢?

Will std::lower_bound be logarithmic for list<>? std::lower_bound 会是 list<> 的对数吗?

No. Quote from documentation:不。引用文档:

for non-LegacyRandomAccessIterators, the number of iterator increments is linear .对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的。


Which containers this function is inteded to use then?那么这个 function 打算使用哪些容器呢?

std::lower_bound is intended for any container that is - or can be - ordered, and doesn't have faster lower bound algorithm that relies on its internal structure - which excludes std::set and std::multiset as mentioned in the documentation. std::lower_bound适用于任何已订购或可以订购的容器,并且没有依赖于其内部结构的更快的下限算法 - 不包括文档中提到的std::setstd::multiset .

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

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