• C++关于erase的复杂度(转载)


    被这个问题困扰了很多次,有必要整理一下。

    当然最好的参考资料就是http://www.cplusplus.com/reference/set/set/erase/ 里的Complexcity部分了,但是有必要记住常见的一些复杂度。否则会掉坑的。

    先来看一下vector的erase复杂度:

    Linear on the number of elements erased (destructions) plus the number of elements after the last element deleted (moving).

    析构函数的复杂度和后面要移动的复杂度,所以一般情况下如果不是删除最后一个(当然删除最后一个直接用pop_back()就可以了)是O(1)外,其它都是O(n),即线性的。

    再来看一下set的erase复杂度如下,它有三种情况的erase,复杂度不同

    (1)iterator erase (const_iterator position);
    (2) size_type erase (const value_type& val);

    >(3) iterator erase (const_iterator first, const_iterator last);

    For the first version (erase(position)), amortized constant.
    For the second version (erase(val)), logarithmic in container size.
    For the last version (erase(first,last)), linear in the distance between first and last.

    第一种方法也就是删除迭代器的位置,复杂度是摊销常数;第二种方法也就是直接删除一个常数,复杂度是log,最后一种删除一段区间,复杂度是O(n)

    可以看到,如果我们的序列本身有序并且删除的位置可以确定或者值确定,那么用vector会很慢,这时可以考虑set或者是手写erase类似这种

  • 相关阅读:
    基于JavaFXWJFXGameEngine游戏引擎介绍与进度
    进程线程与cpu绑定
    [Vim练级攻略] Vim基础操作
    hdu 2159 fate
    python的httplib注意事项
    SQL优化总结
    项目整体开发流程以及配置人员
    hdu 1010 解题报告 Tempter of the Bone
    在centos搭建git服务器时,不小心把/home/git目录删除了,我是怎么恢复的
    int 和bigint差别有多大?
  • 原文地址:https://www.cnblogs.com/zhgyki/p/10567837.html
Copyright © 2020-2023  润新知