Last active
November 6, 2018 01:51
-
-
Save VinGarcia/1973c10b46700960cc369c386bbced60 to your computer and use it in GitHub Desktop.
Medium Article: Making Iterators in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for (auto& i : myContainer) { | |
cout << "My item: " << i << endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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