簡體   English   中英

std::lower_bound 會是 list<> 的對數嗎?

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

假設我有一個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;
}

我會說不是,因為不可能在O(1) list中使用 position 迭代器,但文檔說很奇怪

執行的比較次數是第一個和最后一個之間距離的對數(最多 log2(last - first) + O(1) 比較)。 但是,對於非 LegacyRandomAccessIterators,迭代器增量的數量是線性的。 值得注意的是,std::set 和 std::multiset 迭代器不是隨機訪問,因此它們的成員函數 std::set::lower_bound (resp. std::multiset::lower_bound) 應該是首選。

也就是說,它不建議將這個 function 用於set ,它在內部是 alterady 搜索樹。 那么這個 function 打算使用哪些容器呢? 那么如何插入和維護排序呢?

std::lower_bound 會是 list<> 的對數嗎?

不。引用文檔:

對於非 LegacyRandomAccessIterators,迭代器增量的數量是線性的。


那么這個 function 打算使用哪些容器呢?

std::lower_bound適用於任何已訂購或可以訂購的容器,並且沒有依賴於其內部結構的更快的下限算法 - 不包括文檔中提到的std::setstd::multiset .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM