[英]What's the equivalent to Mathematica's Range[] function in C++?
Mathematica有一個名為Range[]
的函數,它執行以下操作:
Range[0, 10]
Range[-10, 0]
Ant打印:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0}
C ++有這樣的功能嗎?
標准庫中沒有,但來自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, " "));
}
輸出:0 1 2 3 4 5 6 7 8 9 10
似乎很容易創建一個。
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;
}
為了完整起見,以下是使用C ++ 11標准庫和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++; });
這是一個帶有演示的ideone鏈接 。
只有兩個庫提供惰性和O(1)內存數值范圍:
使用SCC (C ++ REPL)和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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.