有关容器的迭代器的问题

thulongkang 2012-07-24 08:18:22
for(vector<Book*>::iterator it=borrowedbook.begin();it!=borrowedbook.end();++it)
{
......
}
我的问题是,如果在循环中有erase的操作,例如borrowedbook.erase(it,it+1);那么,it会不会自动指向下一个元素???
...全文
61 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
thulongkang 2012-07-24
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

erase的返回值:
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 e……
[/Quote]谢谢,很受启发。虽然暂时看着很费劲~
陈厚来 2012-07-24
  • 打赏
  • 举报
回复
楼主的写法要修改下,需要用返回值才行。


for(vector<Book*>::iterator it=borrowedbook.begin();it!=borrowedbook.end();)
{
if(需要删除)
it = borrowedbook.erase(it,it+1);
else
++it;
}
pathuang68 2012-07-24
  • 打赏
  • 举报
回复
erase的返回值:
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.

参考:
http://www.cplusplus.com/reference/stl/vector/erase/
pathuang68 2012-07-24
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
for(vector<Book*>::iterator it=borrowedbook.begin();it!=borrowedbook.end();++it)
{
......
}
我的问题是,如果在循环中有erase的操作,例如borrowedbook.erase(it,it+1);那么,it会不会自动指向下一个元素???
[/Quote]

是的。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧