vector的itrerator支持random access
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 int main() 5 { 6 vector<int>intVector; 7 intVector.push_back(10); 8 intVector.push_back(20); 9 intVector.push_back(30); 10 intVector.push_back(40); 11 intVector.push_back(50); 12 intVector.push_back(60); 13 14 vector<int>::iterator p1 = intVector.begin(); 15 for (; p1 != intVector.end(); p1++) 16 { 17 cout << *p1 <<" " <<&p1<<endl; 18 } 19 //cout <<endl<< "the last" << *p1 << endl; // vector iterator is not dereferencable 20 cout <<endl<< &p1 <<endl; 21 cout << *(--p1) << " "<<&p1<<endl;//60 22 23 cout << *(p1 - 3) <<" "<<&p1<< endl; 24 cout << p1[-3] << " "<<&p1<<endl; 25 cout << *p1 << " " << &p1<< endl; 26 *p1 = 1234; 27 cout << *p1 << " " << &p1 << endl; 28 for (; p1 != intVector.end(); p1++) 29 { 30 cout << *p1 << " " << &p1 << endl; 31 } 32 cout << endl << endl; 33 for (p1=intVector.begin(); p1 != intVector.end(); p1++) 34 { 35 cout << *p1 << " " << &p1 << endl; 36 } 37 cin.get(); 38 return 0; 39 }
输出:
10 00FEFCF4
20 00FEFCF4
30 00FEFCF4
40 00FEFCF4
50 00FEFCF4
60 00FEFCF4
00FEFCF4
60 00FEFCF4
30 00FEFCF4
30 00FEFCF4
60 00FEFCF4
1234 00FEFCF4
1234 00FEFCF4
10 00FEFCF4
20 00FEFCF4
30 00FEFCF4
40 00FEFCF4
50 00FEFCF4
1234 00FEFCF4
PS:①当iterator指向容器中最后一个元素后面一个位置时(空),无法解引用
②iterator相当于指针,对iterator进行++或--时,iterator指向的位置前移或后移,但是iterator本身的地址是不变的,和指针一样