Skip to content

Instantly share code, notes, and snippets.

@AtsushiSuzuki
Created December 19, 2015 00:29
Show Gist options
  • Save AtsushiSuzuki/57c7c9c30fb50d2a082f to your computer and use it in GitHub Desktop.
Save AtsushiSuzuki/57c7c9c30fb50d2a082f to your computer and use it in GitHub Desktop.
C++でpythonのrange
#include <iostream>
#include <iterator>
template <typename T>
class IncreasingNumberIterator: public std::iterator<std::input_iterator_tag, T>
{
private:
T n_;
public:
IncreasingNumberIterator(T n): n_(n) {}
IncreasingNumberIterator(const IncreasingNumberIterator<T>& o): n_(o.n_) {}
IncreasingNumberIterator& operator++() { ++n_; return *this; }
bool operator==(const IncreasingNumberIterator<T>& rhs) { return n_ == rhs.n_; }
bool operator!=(const IncreasingNumberIterator<T>& rhs) { return n_ != rhs.n_; }
T& operator*() { return n_; }
};
template <typename T>
class Range
{
private:
T begin_;
T end_;
public:
Range(T begin, T end): begin_(begin), end_(end) {}
IncreasingNumberIterator<T> begin() { return IncreasingNumberIterator<T>(begin_); }
IncreasingNumberIterator<T> end() { return IncreasingNumberIterator<T>(end_); }
};
template <typename T>
Range<T> range(T begin, T end)
{
return Range<T>(begin, end);
}
int main(int argc, char *argv[])
{
for (auto i : range(0, 10))
{
std::cout << i << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment