Created
December 13, 2022 10:43
-
-
Save ianfun/228d945c1166e7fe5a11bdd2fecf5beb to your computer and use it in GitHub Desktop.
How to write a C++ custom iterator(which can used in std::distance ...).
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
#include <iterator> | |
#include <cstdio> | |
// A number interator | |
struct MyIterator { | |
using value_type = int; | |
using size_type = std::size_t; | |
using difference_type = std::ptrdiff_t; | |
using reference = int&; | |
value_type value; | |
MyIterator(value_type value): value{value} {} | |
MyIterator &operator ++() { | |
value += 1; | |
return *this; | |
} | |
reference operator *() { | |
return value; | |
} | |
reference operator ->() { | |
return value; | |
} | |
bool operator==(const MyIterator &other) { return value == other.value; } | |
bool operator !=(const MyIterator &other) { return !((*this) == other); } | |
}; | |
// the following lines are needed to implement std::iterator_traits, used in std::distance() | |
template <> struct std::iterator_traits<MyIterator> | |
{ | |
using difference_type = MyIterator::difference_type; | |
using value_type = MyIterator::value_type; | |
using reference = MyIterator::reference; | |
using iterator_category = std::forward_iterator_tag; | |
}; | |
int main() { | |
MyIterator Begin = 1; | |
MyIterator End = 10000; | |
printf("distance(a, b) = %zu\n", std::distance(Begin, End)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment