I'm really tired of having to type
for (int iSomething = rangeBegin; iSomething < rangeEnd; ++iSomething)
{
...
}
whenever I want to iterate over an integer range (most IDEs help with the typing, but still it looks so verbose, naming the integer 3 times!)
I wanted something like this:
for (int iSomething : LoopRange(rangeBegin, rangeEnd))
{
...
}
Or if rangeBegin
is 0 (the majority of the cases) then a simple
for (int iSomething : LoopRange(rangeEnd))
{
...
}
My very simple implementation:
class LoopRangeIterator
{
public:
LoopRangeIterator(int value_)
: value(value_){}
bool operator!=(LoopRangeIterator const& other) const
{
return value != other.value;
}
int const& operator*() const
{
return value;
}
LoopRangeIterator& operator++()
{
++value;
return *this;
}
private:
int value;
};
class LoopRange
{
public:
LoopRange(int from_, int to_)
: from(from_), to(to_){}
LoopRange(int to_)
: from(0), to(to_){}
LoopRangeIterator begin() const
{
return LoopRangeIterator(from);
}
LoopRangeIterator end() const
{
return LoopRangeIterator(to);
}
private:
int const from;
int const to;
};
I named it LoopRange
to make it clear that it's for loops and it isn't some general integer range class that you would use for intersecting or building union etc.
Of course this class could be generalized in many ways, but I think if you need more complex functionality (e.g. custom step sizes, double values), then you are doing something special and you are better off writing the explicit for loop.
What do you think about it?
If I use such a thing throughout my project, would it confuse and disturb/distract people too much compared to just using the classic and verbose for(...; ...; ...)
style?
step
argument. It is common enough that Python'srange
built-in functions provides it. \$\endgroup\$step
argument creates a separate type which makes optimisation somewhat easier for the compiler (it can use++
instead of+= var
for the simple case). \$\endgroup\$boost::irange
also takes a step parameter. \$\endgroup\$