2016-09-28 74 views
1

由於stl::map是一個有序映射,插入一個有序數據集會更快嗎?特別是如果我們考慮一個大型數據集?有序地插入到stl :: map更快?

+2

爲什麼不試試看? – NathanOliver

+2

我認爲這取決於具體的實施。 'map'通常使用某種樹形結構 - 紅黑樹或AVL樹或其他類型。插入已排序的序列仍然會每隔一段時間都會觸發重新平衡,這是影響插入性能的唯一因素。也就是說,可能會有一些魔法序列不會觸發重新平衡或不經常觸發它們。未必排序的序列。 –

+2

@WhiZTiM:表現的第二條法則,「永遠不要依賴在一臺機器上測量的結果」。 –

回答

3

當然,排序的數據。

#include <map> 
#include <vector> 

int main() { 
    std::vector<int> data { 0, 1, 2, 3, 4, 5 }; 
    std::map<int, int> result; 
    // From: http://en.cppreference.com/w/cpp/container/map/insert 
    // Amortized constant if the insertion happens in the position just before 
    // the hint, logarithmic in the size of the container otherwise. 
    for(auto i : data) 
     result.insert(result.end(), { i, i}); 
} 
1

是的,的確如此。從大O的角度看,逐個插入N個元素爲O(N * logN),相比之下,構建映射(通常是某種平衡二叉樹)只需要O(N)。

您也可以將GCC的libstdC++實現作爲參考。
gcc/libstdc++-v3/include/bits/stl_map.h