Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@VinGarcia
Last active November 6, 2018 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinGarcia/1973c10b46700960cc369c386bbced60 to your computer and use it in GitHub Desktop.
Save VinGarcia/1973c10b46700960cc369c386bbced60 to your computer and use it in GitHub Desktop.
Medium Article: Making Iterators in C++
for (auto& i : myContainer) {
cout << "My item: " << i << endl;
}
class iterator {
int state;
// ...
/* * * Implementing the expected iterator interface: * * */
T operator*() { return get(); }
iterator& operator++() { next(); return *this; }
iterator operator++(int) { iterator temp(*this); next(); return temp; }
iterator& operator--() { prev(); return *this; }
iterator operator--(int) { iterator temp(*this); prev(); return temp; }
bool operator!=(const iterator& other) const {
return ref != other.ref || cmp(other.state);
}
bool operator==(const iterator& other) const {
return !operator!=(other);
}
// Required implementations if you want to have const
// and non const iterators working interchangeably:
friend struct iterator_tpl::const_iterator<C,T,S>;
// Comparisons between const and normal iterators:
bool operator!=(const const_iterator<C,T,S>& other) const {
return ref != other.ref || cmd(other.state);
}
bool operator==(const const_iterator<C,T,S>& other) const {
return !operator!=(other);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment