Red Banana
Red Banana

Reputation: 742

What's the equivalent to Mathematica's Range[] function in C++?

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?

Upvotes: 8

Views: 820

Answers (4)

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

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}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 4

Jesse Good
Jesse Good

Reputation: 52365

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

Upvotes: 9

Lily Ballard
Lily Ballard

Reputation: 185681

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;
}

Upvotes: 7

Related Questions