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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值