手机
当前位置:查字典教程网 >编程开发 >C语言 >stl容器set,map,vector之erase用法与返回值详细解析
stl容器set,map,vector之erase用法与返回值详细解析
摘要:总结本人在工作中经验教训。在使用list、set或map遍历删除某些元素时可以这样使用:正确使用方法1复制代码代码如下:std::listL...

总结本人在工作中经验教训。

在使用 list、set 或 map遍历删除某些元素时可以这样使用:

正确使用方法1

复制代码 代码如下:

std::list< int> List;

std::list< int>::iterator itList;

for( itList = List.begin(); itList != List.end(); )

{

if( WillDelete( *itList) )

{

itList = List.erase( itList);

}

else

itList++;

}

正确使用方法2

复制代码 代码如下:

std::list< int> List;

std::list< int>::iterator itList;

for( itList = List.begin(); itList != List.end(); )

{

if( WillDelete( *itList) )

{

List.erase(itList++);

}

else

itList++;

}

正确使用方法3

复制代码 代码如下:

std::list< int> List;

std::list< int>::iterator it, next;

for( it = List.begin(), next = it, next ++; it != List.end(); it = next, ++next)

{

if( WillDelete( *it) )

{

List.erase(it);

}

}

注:方法三更为巧妙,但需注意方法三是用前需要判断容器是否为空,否则迭代器会出问题。

我测试得出,set.erase 不返回迭代器,list返回。

vector 删除操作

复制代码 代码如下:

std::vector <PACK_PRINT>::iterator It ;

for(It=printItems.begin();It!=printItems.end();)

{

//我是说这里怎么判断printItems printItems 里PACK_PRINT.bh =0

if( It.bh ==0) //是这样吗?

{//删除

It=printItems.erase(It);

}

else

{//不删除

++It;

}

}

复制代码 代码如下:

std::vector <PACK_PRINT> printItems;

int i = 0;

while(i < printItems.size())

{

if(printItems[i].bh == 0) //这里比如我想把 printItems 时PACK_PRINT.bh =0 的删除如何写哟。另外这样删除有错吗?

{//删除

printItems.erase(printItems.begin() + i);

}

else

{//不删除

++i;

}

}

【stl容器set,map,vector之erase用法与返回值详细解析】相关文章:

C++Primer笔记之关联容器的使用详解

Define,const,static用法总结

C#委托所蕴含的函数指针概念详细解析

Linux vmstat命令实战详细解析

QString和char以及string之间的赋值详解

共用体的定义与应用详细解析

STL list链表的用法详细解析

C++嵌套类与局部类详细解析

static全局变量与普通的全局变量的区别详细解析

CFile与CStdioFile的文件读写使用方法详解

精品推荐
分类导航