Since C++11 introduced the range-based for loop (range-based for in c++11), what is the neatest way to express looping over a range of integers?
Instead of
With C++20
we will have ranges. You can try them by downloading the lastest stable release from it's author, Eric Niebler, from his github, or go to Wandbox. What you are interested in is ranges::views::iota
, which makes this code legal:
#include
#include
int main() {
using namespace ranges;
for (int i : views::iota(1, 10)) {
std::cout << i << ' ';
}
}
What's great about this approach is that view
s are lazy. That means even though views::iota
represents a range from 1
to 10
exclusive, no more than one int
from that range exists at one point. The elements are generated on demand.