C ++ 0x path to replace interval loops (int i ;;) with for-loop range

So, I got into the new C ++ using GCC 4.6, which now has for-loop range loops. I found it really nice to repeat arrays and vectors.

Mostly for aesthetic reasons, I wondered if there is 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 built into the new C ++ standard that allows me to do this? Or do I need to write my own range / iterator class?

+6
c ++ foreach for-loop c ++ 11
source share
1 answer

I do not see him anywhere. But that would be pretty 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 == rx; } 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 (from the top of the head, a little tuning may be required). A pair of iterators should already be in the range, so I believe that you do not need to determine the beginning and end.

+4
source share

All Articles