Skip to content

Instantly share code, notes, and snippets.

@asottile
Created April 2, 2013 17:02
Show Gist options
  • Save asottile/5294000 to your computer and use it in GitHub Desktop.
Save asottile/5294000 to your computer and use it in GitHub Desktop.
Python like xrange in c++ with range fors!
#include <iostream>
using std::cout;
using std::endl;
class Range {
public:
explicit Range(int endValue) : start(0), endValue(endValue) { }
Range(int start, int endValue) : start(start), endValue(endValue) { }
class RangeIterator {
public:
friend Range;
RangeIterator& operator++() {
value += 1;
return *this;
}
RangeIterator operator++(int) {
value += 1;
return RangeIterator(value - 1, end);
}
bool operator==(const RangeIterator& other) const {
return (value == other.value && end == other.end) ||
(ended() && other.ended());
}
bool operator!=(const RangeIterator& other) const {
return !(*this == other);
}
int operator*() const {
return value;
}
private:
RangeIterator(int end) : value(end), end(end) { }
RangeIterator(int value, int end) : value(value), end(end) { }
bool ended() const {
return value >= end;
}
int value;
int end;
};
RangeIterator begin() const {
return RangeIterator(start, endValue);
}
RangeIterator end() const {
return RangeIterator(endValue);
}
private:
int start;
int endValue;
};
int main() {
// Print the numbers 1 to 9
for (int i : Range(10)) {
cout << i << endl;
}
cout << endl << endl;
// Print the numbers 5 to 14
for (int i : Range(5, 15)) {
cout << i << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment