关闭

C++STL笔记

355人阅读 评论(0) 收藏 举报

vector

vector::erase函数

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

Removes from the vector container either a single element (position) or a range of elements ([first,last)).

Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (dequelist).

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.

erase函数要么删作指定位置loc的元素,要么删除区间[start, end)的所有元素.返回值是指向删除的最后一个元素的下一位置的迭代器.
删除vector中所有为8的元素
for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )
    {
        if(* it == 8)
        {
            it = arr.erase(it);
        }
        else
        {
            ++it;//不能在写成for(:,:++it),注意erase的返回值,删除元素后所有元素往前移动it指向删除元素后的后边那个元素
        }
    }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:99151次
    • 积分:1549
    • 等级:
    • 排名:千里之外
    • 原创:66篇
    • 转载:20篇
    • 译文:1篇
    • 评论:20条
    最新评论