手机
当前位置:查字典教程网 >编程开发 >C语言 >C++ vector删除符合条件的元素示例分享
C++ vector删除符合条件的元素示例分享
摘要:C++vector中实际删除元素使用的是容器vecrotstd::vector::erase()方法。C++中std::remove()并不...

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.代码实例

复制代码 代码如下:

#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;

}

C++ vector删除符合条件的元素示例分享1

【C++ vector删除符合条件的元素示例分享】相关文章:

关于C++中的友元函数的一些总结

.h和.cpp文件的区别(zt)详细介绍

C字符串操作函数的实现详细解析

C++ 中的单例模式(普通,2B,文艺)

c++ 虚函数与纯虚函数的区别(深入分析)

c语言全盘搜索指定文件的实例代码

浅析string类字符串和C风格字符串之间的区别

C++实现:螺旋矩阵的实例代码

c 调用python出现异常的原因分析

C数据结构之双链表详细示例分析

精品推荐
分类导航