生成一系列以常量浮点值递增的数字

Generate a series of increasing numbers by a constant floating point value

本文关键字:数字 一系列 常量      更新时间:2023-10-16

我知道iota函数,但它只会工作整数值,因为它正在调用++运算符。

我想生成递增的浮点数,比如0.5[0.5, 1,1.5 .... .,并将它们插入向量

最后我想到的解决方案是:

    double last = 0;
    std::generate(out , out + 10, [&]{
        return last += 0.5; 
    }); 

可以,但是我必须使用一个额外的变量。是否有一个std函数,我缺少像"D语言"中的函数"iota"示例:auto rf = iota(0.0, 0.5, 0.1);

如果你的编译器支持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

也就是说,您可以使用init捕获,而无需在定义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之后使用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));