Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the \"range-based for loops\".
I understand that:
Inspired by BitTickler's comment about how to make it work for non-"container" types, here's a minimal example of something that works for double
s:
class dranged {
double start, stop, step, cur;
int index;
public:
dranged(double start, double stop, double step) :
start(start), stop(stop), step(step),
cur(start), index(0) {}
auto begin() { return *this; }
auto end() { return *this; }
double operator*() const { return cur; }
auto& operator++() {
index += 1;
cur = start + step * index;
return *this;
}
bool operator!=(const dranged &rhs) const {
return cur < rhs.stop;
}
};
Note that the use of <
in the !=
operator maintains the correct invariant, but obviously assumes step
is positive and wouldn't be appropriate everywhere a more general range would be. I've used an integer index
to prevent propagation of floating point error, but have aimed for simplicity otherwise.
This can be used as:
double sum() {
double accum = 0;
for (auto val : dranged(0, 6.28, 0.1)) {
accum += val;
}
return accum;
}
GCC and Clang both produce very reasonable code when compiled with optimisations (i.e. either -Os
or above -O1
for GCC or -O2
for Clang).