遍历std::list过程中删除元素后继续遍历过程
2016-02-18 01:08
344 查看
std::list::erase
Erase elements
Removes from the list container either a single element (position) or a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.
Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence.
返回值
An iterator pointing to 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.
Output:
iVec: 2 3 6 4 1 17 4 9 25 4
iList: 2 3 6 1 17 9 25
或者:
Erase elements
Removes from the list container either a single element (position) or a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.
Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence.
返回值
An iterator pointing to 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.
int iArray[10] = { 2, 3, 6, 4, 1, 17, 4, 9, 25, 4 }; list<int> iList(iArray, iArray + 10); vector<int> iVec; for(list<int>::iterator it = iList.begin(); it != iList.end(); it++) { iVec.push_back(*it); if(*it == 4) { it = iList.erase(it); it--; } } cout << "iVec: "; for(auto& i : iVec) { cout << i << " "; } cout << endl; cout << "iList: "; for(auto& i : iList) { cout << i << " "; } cout << endl;
Output:
iVec: 2 3 6 4 1 17 4 9 25 4
iList: 2 3 6 1 17 9 25
或者:
for(list<int>::iterator it = iList.begin(); it != iList.end();) { iVec.push_back(*it); if(*it == 4) { it = iList.erase(it); } else { it++; } }
相关文章推荐
- java并发编程——线程异常处理\资源共享的问题\ThreadLocal
- 【UVA 11462】 Age Sort(基数排序)
- IntelliJ IDEA 比较当前版本文件与历史文件
- C++复习笔记——初始化列表顺序
- BZOJ3329 Xorequ(数位DP)
- BZOJ3329 Xorequ(数位DP)
- 1086. Tree Traversals Again (25)
- 今天的面试题,我回来鞭尸了!
- 《Android源码设计模式》读书笔记 (6) 第6章 抽象工厂模式
- [LeetCode] Strobogrammatic Number 对称数
- Ruby Unit Test
- sublime 编译java
- 如何查看电脑最大支持多大内存
- vsftpd 本地用户无法登陆 530 Login incorrect
- hdoj 5248 序列变换 【贪心 + 二分】
- Fragment
- c语言:编程找出1000之内的所有完数。
- Visual Studio 2013光标变成方块
- 图解ios程序生命周期
- 1085. Perfect Sequence (25)