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

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

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

Ant he 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?

+8
c ++
source share
4 answers

Not 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

+9
source share

It seems simple enough to create it.

 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; } 
+7
source share

For completeness, here's how you can do it with the standard C ++ 11 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 the ideon with a demo .

+4
source share

There are only two libraries that provide lazy and O (1) numerical memory 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} 
+2
source share

All Articles