C++STL笔记

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指向删除元素后的后边那个元素
        }
    }


posted @ 2012-03-27 14:47  foreverlearn  阅读(135)  评论(0编辑  收藏  举报