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一個元素,導致它后面的元素全部移動到新的位置,所以導致這個元素之后的所有迭代器都失效。
在使用一個函數前應該對它的行為有清楚的了解。謹記。