3 ms·
> With range-based for loops, I often find myself wishing C++ had Python’s xrange function built-in. Built-in to the language would be nice, but C++ is always
by byuu 10y ago
> With range-based for loops, I often find myself wishing C++ had Python’s xrange function built-in.
Built-in to the language would be nice, but C++ is always extremely spartan with its standard library functionality. Thus:
https://gitlab.com/higan/higan/blob/master/nall/range.hpp https://gitlab.com/higan/higan/blob/master/nall/range.hpp
37 lines (without the boilerplate header stuff) and you have:
for(int x : range(20)) ...; //iterate from 0 ... 19
for(int y : rrange(myvector)) ...; //iterate from myvector.size()-1 ... 0
Also supports xrange's offset/stride arguments (it's pretty much exactly Python's xrange object in C++.) And you can add support to do ranges over any class anywhere, eg range(myvector) will pull the length from myvector.size() for you with a simple overloaded function.
Timing tests in extremely critical loops (like convolution kernels eating 100% CPU usage) shows no discernable performance impact at -O2 and above over the traditional C++-style for(int x = 0; x < size; x++) style.