Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 461
Red Banana Avatar asked Dec 17 '12 03:12

Red Banana


2 Answers

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

like image 176
Jesse Good Avatar answered Oct 01 '22 20:10

Jesse Good


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;
}
like image 43
Lily Ballard Avatar answered Oct 01 '22 20:10

Lily Ballard