A
1) Overview
To access the sequential container, the elements in the associative container are made through iterators. An iterator is a variable, similar to a pointer
2) Classification
According to the definition of the different can be divided into four kinds (iterator, const_iterator, Reverse_iterator, Const_reverator_iterator)
3) Definition
4) Example
#include <iostream>#include<vector>using namespacestd;intmain () {vector<int>v; for(intI=0;i<5;++i) v.push_back (i); Vector<int>:: iterator N; for(N=v.begin (); N!=v.end (); + +N) {cout<<*n<<" "; *n *=2;//turn each element into twice times the original.} cout<<Endl; //traversing a container with a reverse iterator for(vector<int>::reverse_iterator J=v.rbegin (); J!=v.rend (); ++j)//pay attention to reversecout<<*j<<" "; return 0;}
++i is more efficient than i++ because of overloaded problems, Post + + generates a temporary object
Functional classification of B iterators
1) Functional classification of iterators (P is an iterator, I is an integral type)
*: Forward iterator. ++p, p++, *p
* *: Bidirectional iterator. Full functionality of the forward iterator and P--,--p
: Random access iterator.
P+=i;
P-=i;
P[i];
<, >, <=, >= comparison
2) The iterator scoring function on different containers
Auxiliary functions for C iterators
1)
*: Advance (p,n); Move the iterator P forward or backward by n elements
* *: Distance (P,Q); Calculates the distance between two iterators
: Iter_swap (P,Q); Swap the value pointed to by a two iterator
Use the above function to include the header file algorithm
2) Example
//helper functions for iterators#include <iostream>#include<algorithm>#include<list>using namespacestd;intMain () {inta[5]={1,2,3,4,5}; List<int>lst (a,a+5);//array names are pointers, like iterators, and are therefore availablelist<int>::iterator p =Lst.begin (); Advance (p,2); cout<<"1:"<<*p; List<int>::iterator q =Lst.end (); Q--; Swap (P,Q); cout<<endl<<"2:"; for(P=lst.begin ();p!=lst.end (); + +p) cout<<*p<<" "; return 0;}
1.3 Iterators-Iterator