生成一系列由常数浮点值递增的数字
Generate a series of increasing numbers by a constant floating point value
我知道 iota 函数,但它只能处理整数值,因为它正在调用 ++ 运算符。
我想生成递增的浮点数,比如 0.5
[0.5, 1, 1.5....],并将它们插入到我的矢量
我想出的最终解决方案是:
double last = 0;
std::generate(out , out + 10, [&]{
return last += 0.5;
});
哪种方法可行,但我必须使用一个额外的变量。是否有我缺少的标准函数,例如 "D language" 示例中的函数 "iota":auto rf = iota(0.0, 0.5, 0.1);
您可以在 iota
:
之后使用 transform
iota(begin(a), end(a), 0);
const auto op = bind(multiplies<double>(), placeholders::_1, .5);
transform(begin(a), end(a), begin(a), op);
或者使用 boost::counting_iterator
:
transform(boost::counting_iterator<int>(0),
boost::counting_iterator<int>(n),
begin(a),
bind(multiplies<double>(), placeholders::_1, .5));
如果你的编译器支持C++ 2014,那么你可以编写
double a[10];
std::generate( a, a + 10,
[step = 0.0] () mutable { return step += 0.5; } );
for ( double x : a ) std::cout << x << ' ';
std::cout << std::endl;
输出将是
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
也就是说,您可以使用初始化捕获,而无需在定义 lambda 的范围内声明额外的变量。
否则,您可以在 lambda 表达式中声明一个静态变量。例如
#include <iostream>
#include <algorithm>
int main()
{
double a[10];
std::generate( a, a + 10,
[] () mutable ->double { static double value; return value += 0.5; } );
for ( double x : a ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
输出将是相同的
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
我知道 iota 函数,但它只能处理整数值,因为它正在调用 ++ 运算符。
我想生成递增的浮点数,比如 0.5 [0.5, 1, 1.5....],并将它们插入到我的矢量
我想出的最终解决方案是:
double last = 0;
std::generate(out , out + 10, [&]{
return last += 0.5;
});
哪种方法可行,但我必须使用一个额外的变量。是否有我缺少的标准函数,例如 "D language" 示例中的函数 "iota":auto rf = iota(0.0, 0.5, 0.1);
您可以在 iota
:
transform
iota(begin(a), end(a), 0);
const auto op = bind(multiplies<double>(), placeholders::_1, .5);
transform(begin(a), end(a), begin(a), op);
或者使用 boost::counting_iterator
:
transform(boost::counting_iterator<int>(0),
boost::counting_iterator<int>(n),
begin(a),
bind(multiplies<double>(), placeholders::_1, .5));
如果你的编译器支持C++ 2014,那么你可以编写
double a[10];
std::generate( a, a + 10,
[step = 0.0] () mutable { return step += 0.5; } );
for ( double x : a ) std::cout << x << ' ';
std::cout << std::endl;
输出将是
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
也就是说,您可以使用初始化捕获,而无需在定义 lambda 的范围内声明额外的变量。
否则,您可以在 lambda 表达式中声明一个静态变量。例如
#include <iostream>
#include <algorithm>
int main()
{
double a[10];
std::generate( a, a + 10,
[] () mutable ->double { static double value; return value += 0.5; } );
for ( double x : a ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
输出将是相同的
0.5 1 1.5 2 2.5 3 3.5 4 4.5 5