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)

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
EC-211 DATA STRUCTURES LECTURE 2. EXISTING DATA STRUCTURES IN C/C++ ARRAYS – A 1-D array is a finite, ordered set of homogeneous elements – E.g. int a[100]
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
By Brandon Sheppard. Use of Iterator  Sequentially move through a collection  Can be very convenient  Phonebook example: Phone number listings stored.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
Stacks. What is a stack? Last-in first-out data structure (LIFO) New objects are placed on top Removal restricted to top object Examples?
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Basic C++ Sequential Container Features
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
CIT241 Prerequisite Knowledge ◦ Variables ◦ Operators ◦ C++ Syntax ◦ Program Structure ◦ Classes  Basic Structure of a class  Concept of Data Hiding.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Templates and Polymorphism Generic functions and classes
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino.
CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Searching Dr. Jose Annunziato. Linear Search Linear search iterates over an array sequentially searching for a matching element int linearSearch(int haystack[],
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Templates Mark Hennessy Dept Computer Scicene NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
Recap Visual Perception and Data Visualization Types of Information Display Examples of Diagrams used for Data Display Planning Requirement for Data Visualization.
CS342 Data Structures End-of-semester Review S2002.
Behavioral Pattern: Iterator C h a p t e r 5 – P a g e 159 Software can become difficult to manage when a variety of different traversals of a variety.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Lecture 7 : Intro. to STL (Standard Template Library)
Cramming for CS 247. FAQ Q: Will you post these slides online? A: Yes.
CS 210 Iterator Pattern October 31 st, Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objective  Standard Template Library.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
CS 261 – Data Structures Hash Tables Hash-like Sorting.
A recap of the STL and more containers Plus an intro to string and file input and output! Lecture 8.
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)
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 18 List ADT Animated Version.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
J. Byrne Polymorphism what it means and when it is used.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Software Design 2.1 STL concepts l Container: stores objects, supports iteration over the objects  Containers may be accessible in different orders 
Python Flow of Control CS 4320, SPRING Iteration The ‘for’ loop is good for stepping through lists The code below will print each element in the.
Learning Objectives 1. Understand how the Small Basic Turtle operates. 2. Be able to draw geometric patterns using iteration.
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Examples (D. Schmidt et al)
Concepts of Programming Languages
Template Method Pattern Iterator Pattern
Flyweight Design Pattern
Starting Out with C++ Early Objects Eighth Edition
Lists in Python.
Introduction to Computer Science for Majors II
Design Patterns Difficult to describe abstractly Elements:
Loops.
Lists - I The List ADT.
Lists - I The List ADT.
Standard Template Library (STL)
Iterator Design Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014
Presentation transcript:

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 (according to Gamma et al., “Design Patterns”) –Provide a way to access elements of a container sequentially without exposing its underlying representation Iterators help provide interface polymorphism –Same interface, but different iterator implementations –Due to underlying containers’ different behaviors We’ll consider iterator interface methods above with –istream, ostream, array, linked list, bi-linked list

CSE 332: C++ STL iterators STL Iterator Syntax and Semantics Pointers and integers are both Gamma et al. iterators for (int * p = &A[0]; p – A < MAX; ++p) { cout << *p << endl; } Pointers (but not integers) are also STL iterators –Relies on associated types tricks we’ll cover later –Use 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 += n via a for loop? Why or why not?

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 STL iterator “value” can be in one of 3 kinds of states: –Dereferenceable (points to a valid location in a range) –Past the end (points just past last valid location in a range) –Singular (points to nothing, like a zero pointer) STL iterators may be compared for equality STL iterators may be copied and assigned Why are STL iterators designed this way?

CSE 332: C++ STL iterators Linear Search Example (Based on Austern) char* strchr(char* s, char c) { while (*s != ‘\0’ && *s != c) { ++s; } return s; } Not a very general solution –Only handles char (not wchar_t, uchar, etc.) –“ Range ” is up to but not including the ‘\0’ Only applies to “ zero terminated ” strings 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* find(char* start, char * end, char c) { while (start != end && *start != c) { ++start; } return start; }

CSE 332: C++ STL iterators A Closer Look at Ranges char* find(char* start, char * end, char c) { while (start != end && *start != c) { ++start; } return start; } 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

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

CSE 332: C++ STL iterators Back to the Linear Search Example Second generalization (we looked at this code before) template Iterator find2 (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) { ++first; } return first; } With both the iterator and value types being template type parameters, the function becomes very generic –Searches any one-dimensional sequence of elements –But, this raises some important issues about the iterator type (especially about what other types are associated with it)

CSE 332: C++ STL iterators An Important Technique: Traits If we want to use iterators in templates, then we need to provide additional info about them –Some information is fairly basic Type for expressing distance between iterators Type obtained when an iterator is dereferenced –Some information is more subtle and advanced Whether or not an iterator can move backward, or be moved an arbitrary distance in constant time Why do we need to provide this information? –For basic info, to write code that compiles –For advanced info, to influence compiler’s matching To do this across diverse types, we need traits

CSE 332: C++ STL iterators Motivating Traits: Iterator’s Value Type Why are traits needed? See example to the left –Illustrates problem of writing a generic swap function template First approach –Work around the problem –Let compiler resolve the value type –Define a forwarding function –Defer implementation to an internal function –Can we improve this? // Austern, pp. 34: can’t write // template // void swap (I i1, I i2){ // T tmp = *i1; // *i1 = *i2; // *i2 = tmp; // } template void swap_impl (I i1, I i2, T t){ T tmp = *i1; *i1 = *i2; *i2 = tmp; } template void swap (I i1, I i2) { swap_impl (i1, i2, *i2); } value type

CSE 332: C++ STL iterators Iterator’s Value Type (continued) Second approach –Declare the value type within a class –Algorithms can then rely on that type in their concepts –A step in the right direction, anyway –What’s the limitation? // Based on Austern, pp. 34 template class MyIterator { public: typedef T value_type; //... private: T * current_; }; template void swap (I i1, I i2) { I::value_type temp; //... }

CSE 332: C++ STL iterators Iterator Traits Third approach: a partial solution –Type indirection –Via an iterator traits class –Why do this? –Have we made progress? // Based on Austern, pp. 35 template struct iterator_traits { typedef typename I::value_type value_type; }; template void swap (I i1, I i2) { iterator_traits ::value_type temp; //... }

CSE 332: C++ STL iterators Iterator Traits (continued) Fourth approach: a complete solution –Different versions of iterator_traits –Uses template specialization –C++ compiler will select the most specific match // Based on Austern, pp. 35 template struct iterator_traits { typedef typename I::value_type value_type; }; template struct iterator_traits { typedef T value_type; }; template struct iterator_traits { typedef T value_type; // a subtlety }; Why do we need this one, too?

CSE 332: C++ STL iterators More About Iterators Associated Types 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 Concept Category –Most refined concept it models –More about how this is used, when we cover STL algorithms in detail how far? units?

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)

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

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 Bidireational Iterator Concept also requires --i, i-- (move from location back to earlier location) Some Models of the Bidirectional Iterator Concept list ::iterator, set ::iterator

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 * Compiler must be able to determine to which category an iterator belongs –Allows it to match an iterator with

CSE 332: C++ STL iterators Advice for Designing Your Own Iterators Use the iterator concept requirements as a checklist –Also good advice for writing containers and functors 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

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

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)

CSE 332: C++ STL iterators How the Iterator Works in this Example From the g 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(); }... };

CSE 332: C++ STL iterators For Next Time Topic: C++ STL Algorithms Assigned Reading –pages pages