在 Python 生成连续的可迭代的序列,常用十分 convenient 的 range()
函数(包含左端点,不包含右端点):
# Python
>>> range(5)
range(0, 5)
>>> for i in range(5):
print(i)
0
1
2
3
4
我们能够在 C++ 中也实现类似的功能呢?
#include <list>
#include <algorithm>
#include <iterator>
#include <iostream>
class IntSeq
{
private:
int x0;
public:
IntSeq(int x) { x0 = x;}
int operator()() const
{
return x0++;
// 此函数对象就有了状态的意味
}
};
std::list<int> range(int first, int end)
{
std::list<int> coll;
std::generate_n(std::back_inserter(coll), end-first, IntSeq(first));
return coll;
}
int main(int, char**)
{
std::list<set> coll = range(0, 10);
for (auto elem: coll):
std::cout << elem << " ";
std::cout << std::endl;
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
return 0;
}