Last active
July 16, 2020 03:02
-
-
Save llllllllll/1872bc0b7f38428564f8930af0efc918 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <cstdlib> | |
#include <compare> | |
#include <ranges> | |
namespace jj { | |
class iota : public std::ranges::view_base { | |
public: | |
iota(long start, long end) : m_start(start), m_end(end) {} | |
iota(long end) : iota(0, end) {} | |
iota() : iota(0, 0) {} | |
iota(const iota&) = default; | |
class iterator { | |
public: | |
using iterator_category = std::random_access_iterator_tag; | |
using value_type = long; | |
using reference_type = const value_type&; | |
using difference_type = long; | |
iterator() : m_ix(0) {} | |
iterator(long ix) : m_ix(ix) {} | |
iterator(const iterator&) = default; | |
reference_type operator*() const { | |
return m_ix; | |
} | |
iterator& operator++() { | |
++m_ix; | |
return *this; | |
} | |
iterator operator++(int) { | |
iterator out = *this; | |
++*this; | |
return out; | |
} | |
iterator& operator--() { | |
--m_ix; | |
return *this; | |
} | |
iterator operator--(int) { | |
iterator out = *this; | |
--*this; | |
return out; | |
} | |
std::strong_ordering operator<=>(const iterator& other) const = default; | |
iterator operator+(difference_type offset) const { | |
return iterator{m_ix + offset}; | |
} | |
iterator operator-(difference_type offset) const { | |
return iterator{m_ix - offset}; | |
} | |
difference_type operator-(iterator other) const { | |
return m_ix - other.m_ix; | |
} | |
value_type operator[](difference_type ix) const { | |
return m_ix + ix; | |
} | |
private: | |
long m_ix; | |
}; | |
iterator begin() const { | |
return iterator{m_start}; | |
} | |
iterator end() const { | |
return iterator{m_end}; | |
} | |
private: | |
long m_start; | |
long m_end; | |
}; | |
} // namespace jj | |
#include <iostream> | |
void print_seq(auto&& seq) { | |
auto end = std::ranges::end(seq); | |
auto it = std::ranges::begin(seq); | |
if (it == end) { | |
std::cout << "{}\n"; | |
} | |
else { | |
std::cout << '{' << *it++; | |
do { | |
std::cout << ", " << *it++; | |
} while (it != end); | |
std::cout << "}\n"; | |
} | |
} | |
int main() { | |
print_seq(jj::iota(-5, 5)); | |
auto negate = [](auto a) { return -a; }; | |
print_seq(jj::iota(-5, 5) | std::views::transform(negate)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment