GLORY | 学习·记录

coding for life

危险的vector::erase

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     vector<int> a;
 8     a.push_back(1);
 9     a.push_back(2);
10     a.push_back(3);
11     a.push_back(4);
12     a.push_back(5);
13     
14     vector<int>::iterator pos=a.begin()+2;
15     vector<int>::iterator temp=pos+1;
16     cout<<"temp now is"<<*temp<<endl;
17     
18     a.erase(pos);
19     
20     cout<<"temp now is"<<*temp<<endl;
21     
22     system("pause");
23     return 0;
24 }

今天在用STL写约瑟夫问题的时候,发现vector的行为总是产生诡异的结果,让我百思不得其解。

看上面代码:
一个vector里面有1到5,总共5个元素。把一个迭代器pos指向第三个元素3,另外一个temp指向第四个元素4,然后调用erase把第三个元素抹掉。
注意,在这个时候继续解引用temp的时候,会发现它指向的元素神奇的变成了5。

问题就处在erase上面,在C++ Reference上面写道:
Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

This invalidates all iterator and references to elements after position or first.

删除vector一个元素,导致它后面的元素全部移动到新的位置,所以导致这个元素之后的所有迭代器都失效。


在使用一个函数前应该对它的行为有清楚的了解。谨记。

posted on 2011-03-11 15:41 meglory 阅读(332) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

随笔分类

随笔档案

最新评论