100 likes | 189 Views
CS 261 - Winter 2009. Iterators - Both Vector and LinkedList. Iterator - basic concept. Problem: How do you provide a user of a container access to the elements, without exposing the inner structure?
E N D
CS 261 - Winter 2009 Iterators - Both Vector and LinkedList
Iterator - basic concept • Problem: How do you provide a user of a container access to the elements, without exposing the inner structure? Think of binding times, or multiple programmers. One writing the container, the other using the collection
A Linked List Loop For example, within the container you wrote a loop such as the following: for (Link p = firstLink; p != null; p = p->next) { This is fine within the container class itself, but we don’t want users of the class to have to know about links
Solution - the Iterator • Solution: define an interface for writing loops. Only provide the methods necessary for writing simple loops: Iterator itr; listIteratorInit (&itr, &aList); While (listIteratorHasNext(&itr)) { current = listIteratorCurrent(&itr); if (current …) listIteratorRemove(&itr); }
Information Hiding • Notice that the iterator loop says nothing about the inner workings of the container • The inner structure of the container is effectively encapsulated, the information is hidden
The Iterator Interface void listIteratorInit (sturct list *l, struct listIterator *litr); int listIteratorHasNext (struct listIterator *litr); eleType listIteratorCurrent (struct listIterator *litr); void listIteratoRemove (struct listIterator *litr); void listIteratorChange (struct listIterator *litr, EleType newValue); void listIteratorAdd (struct listIterator *litr, EleTYpe newValue);
Some simplifying assumptions • Next and hasNext are interleaved • Remove called after next • Cannot call remove twice in a row without a call on hasNext
Iterators are more OOP • Iterators common in OOP languages, where you have polymorphism, interfaces, etc • But idea can be used in any language. • Very intuitive and easy to understand interface, easy to adapt
Your Turn: • OK. Your turn. Todays worksheet is to implement the Dynamic Array Iterator.
Oh. that exam on Monday? • Questions on big-Oh (what is the running time of …) • Conceptual questions related to big-Oh • Implementation questions like we have been doing (how to implement … )