生成一系列以常量浮点值递增的数字
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;
});
可以,但是我必须使用一个额外的变量。是否有一个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));
相关文章:
- 在C++的一系列数字中查找重复模式
- 将一系列数字映射到 CPP 中的值的简单方法
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 根据用户输入从一系列数字中找到一个完美的数字
- 为什么这4个不同的随机数生成器函数会产生相同的一系列数字
- 将目标数字拆分为一系列数字(递归任务)
- 代码打印出一系列无意义的数字
- C++ - 计算一系列数字的数字
- 在一系列数字的间隔内计算数字
- c++程序输出一系列的数字而不是cout
- 我正在尝试创建一个程序,用户在其中输入一系列数字,并且我想列出范围之间的质数
- 用O(1)表示法求一系列数字的平均值——常数时间
- 使用一系列数字有效地初始化 std::set
- C++中一系列数字的组合
- 我怎样才能在一系列数字中找到一个缺失的数字
- 给定一系列数字报告,哪些重复和重复了多少次
- 读取一系列数字
- 在c++中使用随机数生成一系列可重复的数字
- Boost Spirit语法用于识别从一行到向量的一系列数字
- 如何有效地将数组的一系列值与给定的数字相乘