C++ vector 删除符合条件的元素

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.)

2.代码实例

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 
 6 int out(vector<int> &iVec)
 7 {
 8     for(int i=0;i<iVec.size();i++)
 9         cout<<iVec[i]<<ends;
10     cout<<endl;
11     return 0;
12 }
13 
14 int main()
15 {
16     vector<int> iVec;
17     vector<int>::iterator it;
18     int i;
19     for( i=0;i<10;i++)
20         iVec.push_back(i);
21 
22     cout<<"The Num(old):";out(iVec);
23     for(it=iVec.begin();it!=iVec.end();)
24     {
25         if(*it % 3 ==0)
26             it=iVec.erase(it);    //删除元素,返回值指向已删除元素的下一个位置    
27         else
28             ++it;    //指向下一个位置
29     }
30     cout<<"The Num(new):";out(iVec);
31     return 0;
32 }

 执行输出:

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值