4

Possible Duplicate:
Is there a range class in C++11 for use with range based for loops?

I.e. is there a standard range with iterator that will dereference to an integer? I'm thinking about something like this:

for (int i : rangeTo(10)) { ... }
for (int i : rangeFromTo(10, 20)) { .... }
Community
  • 1
  • 1
Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208
  • I would like to avoid allocating an array. – Łukasz Lew Jul 23 '12 at 23:52
  • 1
    What's wrong with good ol' `for(int i=0; i<10;i++)`? – tskuzzy Jul 23 '12 at 23:54
  • 1
    What is the advantage of that over `for(int i = 10; i < 20; ++i)`? – Daniel Fischer Jul 23 '12 at 23:54
  • tskuzzy: possibility of getting space formatting wrong. – Łukasz Lew Jul 24 '12 at 00:08
  • Daniel: possibility of getting inequality wrong. – Łukasz Lew Jul 24 '12 at 00:09
  • 1
    Łukasz, no difference. Well, actually there is. With the classical for loop, I know whether I need a strict or weak inequality. With a range, I'd always have to check whether that includes the upper bound or not, as in Python. – Daniel Fischer Jul 24 '12 at 01:22
  • @DanielFischer: Nonsense. I have yet to see any C or C++ system or library (which *isn't* interfacing with some scripting language) that doesn't use a half-open range. It is absolutely standard in C/C++. Standard algorithms do it. Boost.Range does it. Virtually every for loop over some range of numbers does it. It's so common that if you're not using a half-open range in C/C++, it's usually considered a code smell. – Nicol Bolas Jul 24 '12 at 01:36
  • @NicolBolas Ah, then I didn't get the inequality wrong? I thought I had, per Łukasz's comment. And that would confuse me, since half open is what I'd expect. – Daniel Fischer Jul 24 '12 at 01:41
  • @Daniel - You did get it slightly wrong. :-) Łukasz wants you to use `!=` for inequality, not `<`. We are picky around here! – Bo Persson Jul 24 '12 at 12:28
  • @BoPersson Aha. Guess that makes sense for iterators. – Daniel Fischer Jul 24 '12 at 12:34

1 Answers1

6

No, but there is boost::irange:

#include <boost/range/irange.hpp>
...
for (auto i : boost::irange(10, 20))
{
    std::cout << i << ' ';
}

and boost::counting_range

for (auto i : boost::counting_range(10, 20))
{
    std::cout << i << ' ';
}

The difference is you can add a step, for boost::irange(10, 20, 2).

Jesse Good
  • 50,901
  • 14
  • 124
  • 166