由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - stl container erase in a loop
相关主题
deque的pointer和reference是怎么回事?C++请教,使用c++ vector iterator后输出vector数据出错
A C++ STL questionstl 源代码疑问
C++ vector 一边遍历一边删一个C++的概念问题
c++ template question:说c++不难的欢迎来看看这个
数组弱问关于inserter
一个小程序差点搞死了g++,怎么回事?how to write a function take iterators as parameters?
C++: What is the difference between the two approaches?stl的一个问题
问一下STL里的queue, and stack 遍历的问题 (转载)c++ pointers are iterators, why?
相关话题的讨论汇总
话题: iter话题: deque话题: int话题: endl话题: cout
进入Programming版参与讨论
1 (共1页)
w******7
发帖数: 24
1
#include
#include
int main()
{
using namespace std;
deque que;
for(int i=0; i<10; ++i)
que.push_back(i);
deque::iterator iter = que.begin();
while(iter != que.end()) {
cout << *iter << endl;
++iter;
}
iter = que.begin();
while(iter != que.end())
{
cout << *iter << endl;
que.erase(iter);
}
return 0;
}
results:
0
1
2
3
4
5
6
7
8
9
0
0
1
2
3
4
5
6
7
8
9
Question: Why is there two "0" printed out when erasing? And if change
the code to "que.erase(iter++);", there will be segmentation fault at
the end.
a****o
发帖数: 686
2
iter=que.erase(iter);
or you have undefined behavior.
k******r
发帖数: 2300
3
When you call que.erase(iter), you invalidate the iterator. Try to do it
like this,
iter = que.erase(iter);

【在 w******7 的大作中提到】
: #include
: #include
: int main()
: {
: using namespace std;
: deque que;
: for(int i=0; i<10; ++i)
: que.push_back(i);
: deque::iterator iter = que.begin();
: while(iter != que.end()) {

1 (共1页)
进入Programming版参与讨论
相关主题
c++ pointers are iterators, why?数组弱问
Re: 一道count frequency of all words的面试题 (转载)一个小程序差点搞死了g++,怎么回事?
a simple question for C++ classC++: What is the difference between the two approaches?
请问一个exception题目问一下STL里的queue, and stack 遍历的问题 (转载)
deque的pointer和reference是怎么回事?C++请教,使用c++ vector iterator后输出vector数据出错
A C++ STL questionstl 源代码疑问
C++ vector 一边遍历一边删一个C++的概念问题
c++ template question:说c++不难的欢迎来看看这个
相关话题的讨论汇总
话题: iter话题: deque话题: int话题: endl话题: cout