Concepts of Programming Languages Dr. Mohamed Yehia Dahab
Iterator We often want to access every item in a data structure or collection in turn We call this traversing , iterating over, stepping through or visiting every item Example with a data structure (array): for (int i = 0; i < arr.length(); i++) // do something to arr[i]
Iterator (Cont’) What if we want to traverse a collection of objects? A list, a stack, a queue … Its underlying implementation may not be known to us Java provides a common scheme for stepping through all elements in any collection, called an iterator
What is an Iterator? An iterator is a mechanism used to step through the elements of a collection one by one Each element is “Visited” exactly once
Why use Iterators? Traversing through the elements of a collection is very common in programming, and iterators provide a uniform way of doing so (Reusability) Advantage? Using an iterator, we don’t need to know how the collection is implemented! 2-5
Iterator Interface (in Java) The Java API has a generic interface called Iterator<T> that specifies what methods are required of an iterator public boolean hasNext( ); returns true if there are more elements in the iteration public <T> next( ); returns the next element in the iteration public void remove( ); removes the last element returned by the iterator (optional operation) public void set( <T> Obj); Set the last element returned by the iterator (optional operation) ………. It is in the java.util package of the Java API
Iterator Interface (in Java) (Cont’) For Forward Traversing Next() hasNext() For Backward Traversing Previous() hasPrevious() For Modifying remove set
Iterator Interface (in Java) (Cont’) public static void main (String[] args) { ArrayList al = new ArrayList(); al.add("Mohamed"); al.add("Ragab"); al.add("Ramadan"); Iterator itr = al.iterator(); while(itr.hasNext()) { Object obj = itr.next(); System.out.print(obj + "-->"); } https://ideone.com/4tsiVI
Using an Iterator in an Application Example: Suppose we had an unordered list that was created by ArrayUnorderedList<Person> myList = new ArrayUnorderedList<Person>(); and then had items added to it… // Use iterator to display contents of list Iterator<Person> iter = myList.iterator(); while(iter.hasNext() ) { System.out.println(iter.next()); }
Using an Iterator in an Application // Print just the email addresses now // Note that we have to start a new iteration! iter = myList.iterator(); // start new iteration while(iter.hasNext() ) { System.out.println(iter.next().getEmail()); }
C++ Iterators STL iterator’s value can represent 3 kinds of states: Standard Template Library (STL) STL iterators generalize different uses of pointers STL iterator’s value can represent 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) A closed/open range: [start, end) Singular (points to nothing)
C++ Iterators (Cont’) Pointers and integers support iteration but not all collections are ordinal data structures. for (int * p = A; p – A < MAX; ++p) { cout << *p << endl; } for (unsigned int i = 0; i < MAX; ++i) { cout << A[i] << endl;
Models of C++ Iterators Forward Iterator Linked-list style access (slist) hash_set<string>::iterator Bidirectional Iterator Bi-linked-list style access (list) list<int>::iterator set<string>::iterator Random Access Iterator Array/buffer style access (vector, deque) vector<int>::iterator
C++ Example using namespace std; vector<int> V1; // Add some elements to V1 V1.push_back(1); V1.push_back(5); V1.push_back(7); for(int y=0; y<V1.size(); y++) { cout<<V1[y]; }
C++ Example (Cont’) vector<int>::iterator V1Iterator; for(V1Iterator = V1.begin(); V1Iterator != V1.end(); V1Iterator++) { cout<<*V1Iterator; }
C++ Example (Cont’) the iterators associated with vectors are random access iterators so you could use arithmetic of the form Iterator + I vector<int> myIntVector; vector<int>::iterator myIntVectorIterator; myIntVectorIterator = myIntVector.begin() + 2;
Bidirectional Iterator std::list<int> mylist; for (int i=1; i<=5; ++i) mylist.push_back(i); for (std::list<int>::reverse_iterator riter=mylist.rbegin(); riter!=mylist.rend(); ++riter) std::cout << *riter;
https://ideone.com/YsRGV4 Output Iterators #include <iostream> // std::cout #include <iterator> // std::ostream_iterator #include <vector> // std::vector #include <algorithm> // std::copy int main () { std::vector<int> myvector; for (int i=1; i<10; ++i) myvector.push_back(i*10); std::ostream_iterator<int> out_it (std::cout,“ and "); std::copy ( myvector.begin(), myvector.end(), out_it ); return 0; } https://ideone.com/YsRGV4
Output Iterators #include <iostream> #include <vector> #include <algorithm> #include <fstream> using namespace std; int main () { int ary[] = {2,5,7,2,8,9}; ofstream ofile("TEST.DAT"); // write to STDOUT copy(ary,ary+6,ostream_iterator<int>(cout," - ")); // write into file "TEST.DAT" copy(ary,ary+6,ostream_iterator<int>(ofile,"\n")); ofile.close(); cout << endl; return 0; }