c++ vector erase用法

来源:互联网 发布:网络教育本科学费 编辑:程序博客网 时间:2024/06/05 20:30

文章转载自:http://www.cnblogs.com/xudong-bupt/p/3522457.html

C++ vector中实际删除元素使用的是容器vecrot中std::vector::erase()方法。

C++ 中std::remove()并不删除元素,因为容器的size()没有变化,只是元素的替换。

1.std::vector::erase()

  函数原型:iterator erase (iterator position);  //删除指定元素

       iterator erase (iterator first, iterator last);  //删除指定范围内的元素

  返回值:指向删除元素(或范围)的下一个元素。(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)

#include<iostream>#include<string>#include<vector>using namespace std;int out(vector<int> &iVec){    for(int i=0;i<iVec.size();i++)        cout<<iVec[i]<<ends;    cout<<endl;    return 0;}int main(){    vector<int> iVec;    vector<int>::iterator it;    int i;    for( i=0;i<10;i++)        iVec.push_back(i);    cout<<"The Num(old):";out(iVec);    for(it=iVec.begin();it!=iVec.end();)    {        if(*it % 3 ==0)            it=iVec.erase(it);    //删除元素,返回值指向已删除元素的下一个位置            else            ++it;    //指向下一个位置    }    cout<<"The Num(new):";out(iVec);    return 0;}


原创粉丝点击