Skip to content

Instantly share code, notes, and snippets.

@jonvaldes
Last active December 22, 2015 16:29
Show Gist options
  • Save jonvaldes/6499448 to your computer and use it in GitHub Desktop.
Save jonvaldes/6499448 to your computer and use it in GitHub Desktop.
Simple helper class that, using range-based for loops, allows for integer range loops of the "for(int i=0;i<20;++i)" kind with a cleaner syntax: for(int a : range(0, 10))
a:0
a:1
a:2
a:3
a:4
a:5
a:6
a:7
a:8
a:9
#include <stdio.h>
class range {
public:
struct range_iter {
range_iter(int v) : _value(v) {}
int operator*() const { return _value; }
void operator++() { _value++; }
bool operator!=(const range_iter& other) const { return _value != other._value; }
int _value;
};
range(int from, int cnt) : _from(from), _cnt(cnt) {}
range_iter begin() const { return range_iter(_from); }
range_iter end() const { return range_iter(_from + _cnt); }
private:
int _from,_cnt;
};
int main() {
for(int a : range(0, 10)) {
printf("a:%d\n", a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment