Iterators(cont.) Now we rewrite findo to meet request 4 template <typename IteratorType, typename ElemType> IteratorType find (IteratorType first, Iterator Type last, const ElemType& value) for first != last; first++) if ( first = Value) return first return last;
Iterators (cont.) ◼ Now we rewrite find() to meet request 4 template <typename IteratorType, typename ElemType> IteratorType find(IteratorType first , IteratorType last , const ElemType& Value) { for (; first != last; first++) { if (*first == Value) return first; } return last; }
Iterators(cont.) 圆 And how to use const int asize 8: int ia[ asize]={1,1,23,58,13,21} vector<int> ivec(ia, ia asize);//using the array to initialize the vector list<int> List(ia, ia asize); //using the array to initialize the list int * pa find (ia, ia asize, 1024) if (pa != ia asize) //found. vector<int>: :iterator it_v= find(ivec begin, ivec endo, 1024); if (it v!= ivecendo) / /found. list<int>: iterator it find (dlist, begin, ilist. endo, 1024) if (it_!= ilist. endo //found
Iterators (cont.) ◼ And how to use const int asize = 8; int ia[asize] = { 1, 1, 2, 3, 5, 8, 13, 21}; vector<int> ivec(ia, ia + asize); //using the array to initialize the vector list<int> ilist(ia, ia + asize); //using the array to initialize the list int *pa = find(ia, ia + asize, 1024); if (pa != ia + asize) //found… vector<int>::iterator it_v = find(ivec.begin(), ivec.end(), 1024); if (it_v != ivec.end()) //found… list<int>::iterator it_l = find(ilist.begin(), ilist.end(), 1024); if (it_l != ilist.end()) //found…
Iterators(cont.) u Compare the following iterators int*p= &v[ O l; vector< int >:iterator it1, vector< int >; const iterator it2 vector< string >::iterator it3 list< int >:: iterator it4 t1=p//? it1=it2;// it=it3;//? t1=it;//?
Iterators (cont.) ◼ Compare the following iterators int* p = &v[ 0 ]; vector< int >::iterator it1; vector< int >::const_iterator it2; vector< string >::iterator it3; list< int >::iterator it4; it1 = p; //? it1 = it2; //? it1 = it3; //? it1 = it4; //?
Iterators(cont.) Linear Range a In Generic Programming, containers are regarded linear ranges and manipulated via iterators a The iterator pair [first, last), is used frequently to epresent linear range Benefits The number of elements in [first, last) is last-first Lp, p)is eligible to represent a null range
Iterators (cont.) ◼ Linear Range ◼ In Generic Programming, containers are regarded linear ranges and manipulated via iterators ◼ The iterator pair [first, last) , is used frequently to represent linear range ◼ Benefits ◼ The number of elements in [first, last) is last – first ◼ [p, p) is eligible to represent a null range
Standard sTl containers and Their Usage
Standard STL Containers and Their Usage