zoukankan      html  css  js  c++  java
  • 关于vector erase的使用

    看到几篇文章关于vector erase的使用,都会不约而同的提及 这里使用erase有些误区在里面,于是乎看到有的上代码,有的作精细分析,个人以为,授人鱼不如授人以渔,给出最权威的解释即可:

    在msdn的官网解释如下:

      http://msdn.microsoft.com/zh-tw/data/aa242956

    vector::erase

    vector::erase

    iterator erase(iterator it);
    iterator erase(iterator first, iterator last);

    The first member function removes the element of the controlled sequence pointed to by it. The second member function removes the elements of the controlled sequence in the range [first, last). Both return an iterator that designates the first element remaining beyond any elements removed, or end() if no such element exists.

    Erasing N elements causes N destructor calls and an assignment for each of the elements between the insertion point andthe end of the sequence. No reallocation occurs, so iterators and references become invalid only from the first element erased through the end of the sequence.  

      注意这最后一句,相比很多的错误就是忽略了这句话:这里是说当删除一个元素或者多个元素后,如,删除N个元素,解析器destructor亦是被调用N次用于释放相应的被删除元素,同时,将剩余的元素再次联结起来构成新的vector/list/ etc,但是这期间并不是重新分配空间用于盛放新的vector/list, 总之,原有的迭代器所指向的容器已经是昨是今非啦,这样,原有的迭代器就会部分失效,从首个删除的位置到最后一个被删除的位置这一区间内迭代器失效(内容已经被删除了嘛),原迭代器对这个地址段内的任何操作都是非法的,因此,很多的erase操作错误原因就水落石出了吧。。。。

     在另外一个链接: www.cplusplus.com 

      其中说的更为明白,有兴趣的话可以参考阅读,不过还是英文,耐心看看,大有收获。

      此致敬礼。

  • 相关阅读:
    Leetcode第七题——数的反转
    Leetcode第六题——横向遍历ZIGZAG数组
    26 将查询结果插入到一张表中?
    25 表的复制
    24 insert 语句插入数据
    23 创建表
    22 limit(重点中的重点,以后分页查询全靠它了。)
    21 union(可以将查询结果集相加
    20 子查询
    19 连接查询
  • 原文地址:https://www.cnblogs.com/superniaoren/p/2127114.html
Copyright © 2011-2022 走看看