std::set/std::map的"建议插入"

std::set和std::map的插入函数, 通常使用的是这个: pair<iterator, bool> insert(const value_type& x)

set和map往往用二叉平衡树一类的结构实现, 在最差的情况下(例如, 完全升序或者降序排列), 会导致一直调整"平衡", 导致开销很大

这时候, 可以使用这个: iterator insert(iterator pos, const value_type& x)即"建议插入", 建议在pos之前插入元素. 如果"建议"正确, 插入耗时将是常数级别的

试验代码:

const long MAX = (long)5e6;
int main()
{
    set<long> set1, set2, set3, set4;
    long i;
    
    int64_t t0 = time(NULL);
    for (i=0; i<MAX; i++) {
        set1.insert(i);
    }
    int64_t t1 = time(NULL);
    cout << "normal asc insert: " << t1 - t0 << endl;
    
    for (i=0; i<MAX; i++) {
        set2.insert(set2.end(), i);
    }
    int64_t t2 = time(NULL);
    cout << "end() insert: " << t2 - t1 << endl;

    for (i=MAX; i>0; i--) {
        set3.insert(i);
    }
    int64_t t3 = time(NULL);
    cout << "normal desc insert: " << t3 - t2 << endl;
    
    for (i=MAX; i>0; i--) {
        set4.insert(set4.begin(), i);
    }
    int64_t t4 = time(NULL);
    cout << "begin() insert: " << t4 - t3 << endl;
    
    return 0;
}

运行结果:

normal asc insert: 8
end() insert: 1
normal desc insert: 8
begin() insert: 1


参考资料:

http://www.velocityreviews.com/forums/t290788-set-insert-with-hint.html


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章