8

Mathematica has a function called Range[] that does the following:

Range[0, 10]
Range[-10, 0]

Ant it prints:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0}

Does C++ have such a function?

Red Banana
  • 742
  • 2
  • 7
  • 13

4 Answers4

9

None in the standard library, but from boost::range:

#include <iostream>
#include <iterator>
#include <boost/range/irange.hpp>
#include <boost/range/algorithm/copy.hpp>

int main()
{
    boost::copy(boost::irange(0, 11), 
                std::ostream_iterator<int>(std::cout, " "));
}

Output: 0 1 2 3 4 5 6 7 8 9 10

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

Seems easy enough to create one.

std::vector<int> range(int from, int to) {
    std::vector<int> result;
    result.reserve(to-from+1);
    for (int i = from; i <= to; ++i) {
        result.push_back(i);
    }
    return result;
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
4

For completeness, here is how you can do it with the C++11 standard library and lambdas:

vector<int> v;
int counter = -3;    // The initial value
generate_n(
    back_inserter(v) // Where to insert
,   10               // how many items
,   [&counter] () -> int { return counter++; });

Here is a link to ideone with a demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

There is only two libraries that provide lazy and O(1) memory numeric ranges:

With SCC (C++ REPL) and RO:

scc 'range(0,10)'
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

scc 'range(-10,0)'
{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0}
Leonid Volnitsky
  • 8,854
  • 5
  • 38
  • 53