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()) {
|
|