zoukankan      html  css  js  c++  java
  • 正确使用stl vecotr erase函数

    erase函数要么删作指定位置loc的元素,要么删除区间[start, end)的所有元素.

    返回值是指向删除的最后一个元素的下一位置的迭代器

    Parameters

    All parameters are of member type iterator, which in vector containers are defined as a random access iterator type.

    position
    Iterator pointing to a single element to be removed from the vector.
    first, last
    Iterators specifying a range within the vector to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.

    Return value

    A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.

    删除值为3的元素,按说it = vec.erase(it); 是正确的,但是我实验发现 it = vec.erase(it);和 vec.erase(it);都可以work,没有crash。

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        vector<int> vec;
        vec.push_back(1);
        vec.push_back(2);
        vec.push_back(3);
        vec.push_back(4);
        vec.push_back(5);
    
        for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
        {   
            if(*it == 3)
            {   
                it = vec.erase(it);
                //vec.erase(it);
                cout << *it << "CCC" << endl;
                it --; 
            }   
            else
                cout << *it << endl;
        }   
        return 0;
    }

    //注意上面不能写成

        
    /*
            for(vector<int>::iterator it=arr.begin(); it!=arr.end(); it ++)
            {
                if(* it == 8)
                {
                    arr.erase(it); //在erase后,it失效,并不是指向vector的下一个元素,it成了一个“野指针”。

                }
            }
          
        */

  • 相关阅读:
    QT基础知识总结(一)
    二叉树知识总结(二)
    二叉树知识总结(一)
    C++ 封装,继承,多态总结
    Win API学习笔记——文件系统(二)
    Win API学习笔记——文件系统(一·)
    Go项目: package project/name is not in GOROOT
    创建`Vue-CLI`项目
    npm与yarn介绍与常用命令
    Powershell-"无法加载文件,因为在此系统上禁止运行脚本"
  • 原文地址:https://www.cnblogs.com/diegodu/p/4616505.html
Copyright © 2011-2022 走看看