首页 > 编程语言 > 详细

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

时间:2019-03-20 21:31:52      阅读:439      评论:0      收藏:0      [点我收藏+]

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

当然最好的参考资料就是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类似这种

 

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

原文:https://www.cnblogs.com/zhgyki/p/10567837.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!