Presentation is loading. Please wait.

Presentation is loading. Please wait.

. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.

Similar presentations


Presentation on theme: ". STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and."— Presentation transcript:

1 . STL: C++ Standard Library (continued)

2 STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and operator— u Different types of iterators - to support read, write and random access u Containers define their own iterator types u Changing the container can invalidate the iterator

3 Iterator Types u Output: write only and can write only once u Input: read many times each item u Forward: supports both read and write u Bi-directional: supports also decrement u Random: supports random access (just like C pointer)

4 Iterators & Containers Bidirectional iterators: u list, map, set Random access iterators: u vector, deque Input/output/forward iterators: u iostreams

5 Iterators & Containers Every STL container T provides: class T { … typedef … iterator // iterator type T iterator begin(); // first element of the container iterator end(); // element after last of the container };

6 Iterators & Containers Typical code will look like: Container C … Container::iterator i for( i = C.begin(); i != C.end(); i++) // do something with *i

7 Iterators & Containers Iterators allow to access/modify elements Container C; Container::iterator i,j;  C.insert(i,x) – insert x before i  C.insert(i,first,last) – insert elements in [first,last) before i  C.erase(i) – erase element i points to  C.erase(i,j) – erase elements in range [i,j)

8 Iterator validity u When working with iterators, we have to remember that their validity can change u Whats wrong with this code? Container C; C::iterator i; for( i = C.begin(); i != C.end(); i++ ) if( f( *i ) ) // some test C.erase(i); // remove this element

9 Iterator validity Two cases: u list, set, map  i is not a legal iterator u vector  i points to the element after (skips one element in the vector) In either case, this is not what we want…

10 Iterator validity Second try… Container C; C::iterator i = C.begin(); while( i != C.end() ) { C::iterator j = i++; if( f( *j ) ) // some test C.erase(j); // remove this element } Works for set, map, list, not vector or deque

11 Iterator Validity u Third try… Container C; C::iterator i; for(i = C.begin(); i != C.end(); i++ ) if( f( *i ) ) // some test i= C.erase(i); // erase returns the iterator for the next element in the container. Still does not work for vector.

12 Iterators and Map Suppose we work with map dictionary; map ::iterator i; … i = dictionary.begin(); What is the type of *i ?

13 Iterators and Map Every STL container type Container defines Container::value_type Type of elements stored in container  This is the type returned by an iterator Container::value_type Container::iterator operator*();

14 Iterators and Map u Ok, so what type of elements does a map return (what is value_type of map) ? Recall  map keeps pairs  KeyType key – “key” of entry  DataType value – “value” of entry

15 Pairs template struct pair { typedef T1 first_type; typedef T2 first_type; T1 first; T2 second; pair( const T1& x, const T2& y ) : first(x), second(y) {} };

16 Map value_type template< class Key, class T, class Cmp = less > class map { public: typedef pair value_type; typedef Key key_type; typedef T data_type; typedef Cmp key_compare; };

17 Using map iterator map dict; … map ::iterator i; for( i = dict.begin(); i != dict.end(); i++ ) { cout first << “ “ second << “\n”; } [See dictionary.cpp]

18 Iterators and Assoc. Containers Additional set of operations:  iterator C::find(key_type const& key) Return iterator to first element with key. Return end() if not found  iterator C::lower_bound(key_type const& key) Return iterator to first element greater or equal to key  iterator C::upper_bound(key_type const& key) Return iterator to first element greater than key

19 Iterators & Streams Can access iostreams through iterators: istream_iterator in(cin); istream_iterator endOfInput; ostream_iterator out(cout); while( in != endOfInput ) { string s = *in++; *out++ = s; *out++ = “ “; } see useStreamIterators.cpp

20 Inserters istream_iterator in(cin); istream_iterator endOfInput; vector vect; back_insert_iterator > back(vect); // copy input words into vector… while( in != endOfInput ) *back++ = *in++; // same as: vect.push_back(*in++)

21 Inserters Inserters are output iterators u back_insert_iterator ( C& c) Insert at back of c u front_insert_iterator ( C& c) Insert at front of c u insert_iterator (C& c, Iter i) Insert at just before i Allow to write into containers in generic algorithms

22 Do-it-yourself iterators u You can create iterators Check list:  Define the appropriate operators  Ensure copy constructor/operator  Define the right typedefs use inheritance from iterator class [See TokenIterator.h]

23 Sequence Adapters u Adapters of basic containers u Very easy, but limited interface stack  provides push, pop, top, size and empty queue  also provides back priority_queue u provides same interface as stack u uses a compare function object

24 Container summary []List opsFront opsBack opsIterators vectorconstn+const+Random listconst Bi-direct dequeconstn Random stackconst queueconst priority_queuelog(n) maplog(n)log(n)+Bi-direct setlog(n)+Bi-direct

25 Algorithms Overview u Sequence operations  Non modifying: for_each, find, count, search, mismatch, equal  Modifying: transform, copy, swap, replace, fill, generate, remove, unique, reverse, rotate, random_shuffle u Sorted sequences operations  sort, lower_bound, upper_bound, equal_range, binary_search, merge, includes, set_union, intersection, set_difference, set_symmetric_difference

26 Algorithms u Most STL algorithms works on sequences u Sequences are passed as two iterators:  beginning element  element one after last u Algorithms depend on iterator type not on container type pq sequence [p,q)

27 Copy template Out copy(In first, In last, Out res) { while (first != last) *res++ = *first++; return res; } See useCopy.cpp

28 Non-modifying Sequence Algorithms  In find(In first, In last, const T& val) find the first occurence of val in the sequence  In find_if(In first, In last, Pred p) find the first element satisfying p  I1 find_first_of(I1 f1, I2 l1, I2 f2, I2 l2) find the first match between two sequences.  I1 search( I1 f1, I1 l1, I2 f1, I2 l2 ) search for the sequence f2...l2 inside f1..l1

29 Sorted Sequence Algorithms  sort(In first, In last[, class cmp]) find the first occurence of val in the sequence  In lower_bound(In first, In last, T const & val[, class cmp]) find the first element not less than val  bool binary_search(In first, In last, T const & val[, class cmp]) check if val appears in the sequence  Out merge( I1 f1, I1 l1, I2 f1, I2 l2, Out out ) merge two sorted sequences and write the merged sequence onto the output iterator out

30 Ex8: Huffman Code u Very easy !! u Compression of text files, implement using STL: u Priority queue u Map u Vector/deque u Function objects u Copy (algorithm) u The more STL you’ll use the more you’ll learn.


Download ppt ". STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and."

Similar presentations


Ads by Google