Dave Purdum
An object that traverses over a collection (array, vector, tree, hashmap...)
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;
}
}
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() { }
};
Start with any number n. To get the next number...
Set n = 3n + 1
Set n = n/2
class Collatz {
// Properties...
// Constructor
Collatz(int start) { }
bool hasNext() { }
int next() { }
};
// 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/