Iterators and Higher order functions

Dave Purdum

Iterators

An object that traverses over a collection (array, vector, tree, hashmap...)

Start

NEXT

END

Where to start?

How to move to the next element?

When to stop?

int main() {
    
    int A[] = {2,3,5,7,11,13};
    
    ArrayIter* iter = new ArrayIter(A, 6);
    
    while (iter->hasNext()) {
    	cout << iter->next() << endl;
    }
}

Lets write it!

int main() {
    
    int A[] = {2,3,5,7,11,13};
    
    ArrayIter* iter = new ArrayIter(A, 6);
    
    while (iter->hasNext()) {
    	cout << iter->next() << endl;
    }
}
class ArrayIter {
    
    // Properties...
    
    // Constructor
    ArrayIter(int* A, int length) { }
    
    bool hasNext() { }
    
    int next() { }
};

Exercise: Collatz Sequence

Start with any number n. To get the next number...

If odd

If EVEN

Set n = 3n + 1

Set n = n/2

12  6  3  10  5  16  8  4  2  1  4  2  1...

class Collatz {
    
    // Properties...
    
    // Constructor
    Collatz(int start) { }
    
    bool hasNext() { }
    
    int next() { }
};

C++ Iterators in Reality

// std::iterator example
#include <iostream>     // std::cout
#include <iterator>     // std::iterator, std::input_iterator_tag

class MyIterator : public std::iterator<std::input_iterator_tag, int>
{
  int* p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
  int& operator*() {return *p;}
};

int main () {
  int numbers[]={10,20,30,40,50};
  MyIterator from(numbers);
  MyIterator until(numbers+5);
  for (MyIterator it=from; it!=until; it++)
    std::cout << *it << ' ';
  std::cout << '\n';

  return 0;
}

http://www.cplusplus.com/reference/iterator/iterator/

Iterators and Higher Order Functions

By rutrum

Iterators and Higher Order Functions

Talk for Butler ACM describing iterators and how higher order functions play a role in functions like map, filter, reduce, fold, etc.

  • 339