So I've been getting into the new C++ using GCC 4.6 which now has range-based for-loops. I've found this really nice for iterating over arrays and vectors.
For mainly aesthetic reasons I wondered if there was a way to use this to replace the standard
for(int i = min; i < max; i++) {}
with something like
for(int& i : std::range(min, max)) {}
Is there something natively built into the new C++ standard that allows me to do this? Or do I have to write my own range/iterator class?
I don't see it anywhere. But it would be rather trivial:
class range_iterator : public std::input_iterator<int, int> {
int x;
public:
range_iterator() {}
range_iterator(int x) : x(x) {}
range_iterator &operator++() { ++x; return *this; }
bool operator==(const range_iterator &r) const { return x == r.x; }
int operator*() const { return x; }
};
std::pair<range_iterator, range_iterator> range(int a, int b) {
return std::make_pair(range_iterator(a), range_iterator(b));
}
should do the trick (off the top of my head; might need a little tweaking). Pair of iterators should already be range, so I believe you shouldn't need to define begin and end yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With