C++0x way to replace for(int i;;) range loops with range-based for-loop
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)) 开发者_JAVA百科{}
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.
精彩评论