Skip to content

Instantly share code, notes, and snippets.

@ianfun
Created December 13, 2022 10:43
Show Gist options
  • Save ianfun/228d945c1166e7fe5a11bdd2fecf5beb to your computer and use it in GitHub Desktop.
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 ...).
#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