Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)

Similar presentations


Presentation on theme: "CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)"— Presentation transcript:

1 CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container) –Give access the current element to which it points An iterator may be able to do 2 other important things –Move to point to the next element in a range –Be tested for having run through the entire range Intent (based on Gamma et al., “Design Patterns”) –Provide a way to access elements of a container sequentially without exposing its underlying representation Iterators help provides polymorphism –Same interface, but different iterator implementations –Underlying containers give different behaviors We’ll consider iterator interface methods above with –istream, ostream, array, linked list, bi-linked list

2 CSE 332: C++ STL iterators Overview of STL Iterators STL iterators generalize different uses of pointers Interface between algorithms and data structures –Algorithm manipulates iterators, not containers Iterator “value” can be in one of 3 kinds of states: –Dereferenceable (points to a valid location, like in an array) –Past the end (points just past last valid location) –Singular (points to nothing, like a zero pointer) Iterators may be compared for equality Iterators may be copied and assigned The iterator family consists of five concepts: –Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator –We’ll look at each of these categories in detail

3 CSE 332: C++ STL iterators STL Iterator Syntax and Semantics Pointers and integers are iterators for (int * p = &A[0]; p – A < MAX; ++p) { cout << *p << endl; } Pointers (not integers) are also STL iterators –Relies on associated types tricks we’ll cover later –Uses traits based on typedef/struct/specialization The compiler can only check the syntax Iterator definition must provide good semantics –Including memory, aliasing, time complexity –Is it ok to implement p+= as a for loop?

4 CSE 332: C++ STL iterators Linear Search Example char* strchr(char* s, int c) –From Austern “Generic Programming and the STL” –Sequential (linear) search for the first instance of character c in C-style string s Not a very general solution –Only handles char (not wchar_t, uchar, etc.) –“ Range ” is always defined from start to ‘\0’ A “ null terminated ” or “ zero terminated ” string in C/C++ First generalization: use a proper range –Provide an integer range length (how far to count) –Provide a first and last pointer into the array char* findl(char* start, char* end, int c)

5 CSE 332: C++ STL iterators Introduction to Ranges char* findl(char* start, char* end, int c); searches all positions in the string (from start up to but not including end ) for a position with value c –A closed/open range: [start, end) A few questions about ranges to consider – At what position is ‘\0’ in “hello” ? –What is the last element in [0,1) ? Closed/open ranges help avoid off-by-one errors –The number of elements in the range [start, end) is end - start

6 CSE 332: C++ STL iterators Some Definitions Related to Ranges A valid range can be traversed safely with an iterator An empty range [p,p) is valid If [first, last) is valid and non-empty, then [first+1, last) is also valid –Proof: iterative induction on the range If [first, last) is valid –and position mid is reachable from first –and last is reachable from mid –then [first, mid) and [mid, last) are also valid If [first, mid) and [mid, last) are valid, then [first, last) is valid –Proof: divide and conquer induction on range

7 CSE 332: C++ STL iterators Iterator Concept Hierarchy Input IteratorOutput Iterator Forward Iterator Bidirectional Iterator Random Access Iterator value persists after read/write values have locations can express distance between two iterators read or write a value (one-shot) Linked-list style access ( slist ) Bi-linked-list style access ( list ) Array/buffer style access ( vector, deque ) “destructive” read at head of stream ( istream ) “transient” write to stream (ostream)

8 CSE 332: C++ STL iterators Input/Output Iterator Concepts & Models Important Input Iterator Concept Expressions *i (read value at the head of the stream) i->m (access member through iterator) ++i, i++ (move the iterator to next element in stream) Some Models of the Input Iterator Concept istream_iterator, most other STL iterators Important Output Iterator Concept Expressions X y(x), X y=x, y = x (copy construct / assign iterators) *x = t, (write value t into the stream) x++, ++x (move the iterator to next element in stream) Some Models of Output Iterator Concept front_insert_iterator back_insert_iterator ostream_iterator

9 CSE 332: C++ STL iterators Forward/Bidirectional Iterator Concepts & Models Important Forward Iterator Concept Expressions –Can pass same forward iterator in multiple arguments X x, X(),(default construction) ++i, i++ (move from location to location) *i (non-destructive access to container element) Some Models of the Forward Iterator Concept slist ::const_iterator hash_set ::iterator Important Bidireational Iterator Concept Expressions --i, i-- (move from location back to earlier location) Some Models of the Bidirectional Iterator Concept list ::iterator, set ::iterator

10 CSE 332: C++ STL iterators Random Access Iterator Concepts & Models Important Random Access Iterator Concept Expressions i+=n, i-=n (moving iterator given distance in constant time) i+n, n+i, i-n, n-i, i-j, i<j (iterator arithmetic) i[n], i[n]=t (indexing a container using an iterator) –Thought Question: we can express the distance between two Forward Iterators, so why don’t those iterators have i-j or i<j ? Some Models of the Random Access Iterator Concept vector ::iterator deque ::iterator char *

11 CSE 332: C++ STL iterators Associated Types: Key Ideas to Consider Difference Type –Type for “distance” between two iterators i1 and i2 –E.g., ptrdiff_t Reference, Value Types –For T *p, value type is T, *p normally returns T & –For const T *p, value type is const T, *p gives const T & Iterator Category –What concept(s) it models how far? units?

12 CSE 332: C++ STL iterators Advice for Designing Your Own Iterators Use the iterator concept requirements as a checklist Make you support both constant and mutable objects Define associated types appropriately –More on this in the lecture on generic programming Provide as wide an iterator interface as possible without loss of efficiency Obey the aliasing rule we talked about with pointers –Two iterators equal if and only if they point to same variable i == j &(*i) == &(*j) *i == *j

13 CSE 332: C++ STL iterators Advice for Using Iterators Write a concept expression checklist for iterator developers to use in designing their iterators Watch out for empty ranges Require as narrow an iterator interface as possible without loss of efficiency –Avoid over-constraining unnecessarily –E.g., requiring just == and and != Use selective dispatching techniques to provide both efficiency and generality

14 CSE 332: C++ STL iterators Example of Using Iterators in the STL From Austern, pp. 355 Copies values from an istream into a vector What exactly is going on here? int main () { vector V; copy (istream_iterator (cin), istream_iterator (), back_inserter (V)); } (Thanks to Morgan Deters for this example)

15 CSE 332: C++ STL iterators How the Iterator Works in this Example From the g++ 2.95.2 STL source code : template class istream_iterator {... public: istream_iterator() : _M_stream(&cin), _M_end_marker(false) {} istream_iterator(istream& __s) : _M_stream(&__s) { _M_read(); }... };

16 CSE 332: C++ STL iterators For Next Time Topic: C++ STL Algorithms Assigned Reading –pages 930-933 pages 1102-1128


Download ppt "CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)"

Similar presentations


Ads by Google