But how would one do:
x = range(0,20,2)
除了使用std::generate()
(请参见其他答案)之外,您还可以向std::iota()
提供自己的一元函数,只需将其命名为operator++()
:
#include <iostream>
#include <functional>
#include <numeric>
#include <vector>
template<class T>
struct IotaWrapper
{
typedef T type;
typedef std::function<type(const type&)> IncrFunction;
type value;
IncrFunction incrFunction;
IotaWrapper() = delete;
IotaWrapper(const type& n, const IncrFunction& incrFunction) : value(n), incrFunction(incrFunction) {};
operator type() { return value; }
IotaWrapper& operator++() { value = incrFunction(value); return *this; }
};
int main()
{
IotaWrapper<int> n(0, [](const int& n){ return n+2; });
std::vector<int> v(10);
std::iota(v.begin(), v.end(), n);
for (auto i : v)
std::cout << i << ' ';
std::cout << std::endl;
}
输出: 0 2 4 6 8 10 12 14 16 18
演示
以下是如何实现Range()
的想法:
struct Range
{
template<class Value, class Incr>
std::vector<Value> operator()(const Value& first, const Value& last, const Incr& increment)
{
IotaWrapper<Value> iota(first, [=](const int& n){ return n+increment; });
std::vector<Value> result((last - first) / increment);
std::iota(result.begin(), result.end(), iota);
return result;
}
};
Demo
std::transform
。 - Jaa-crange
令人困惑,它根据参数数量改变其位置参数的含义。对我来说,等价功能在iota
和generate
(+ lambda)之间分配是一个优点。 - Caleth