用线性增加的值填充向量 [英] Populate a vector with linearly increased values
问题描述
我会用线性增加的值填充/初始化一个向量.例如,对于这个向量中的每个元素,我希望下一个元素比前一个元素多 a
.或者 kth
元素的值为 k*a
I'd to populate/initialize a vector with linearly increased value. For example, for every element in this vector, I'd like the next one is a
more than the previous. Or the kth
element has a value of k*a
像这样:
float a = 1.132;
vector<float> v(100);
for (int n = 0; n < 100; ++n)
{
v[n] = n*a;
}
有没有更优雅的方法来做到这一点?谢谢.
Is there a more elegant way to do it? Thanks.
一个 matlab 例子是 linspace(beginning value, end value, number of points)
A matlab example would be the linspace(beginning value, end value, number of points)
linspace(1,5, 6)
ans =
1.0000 1.8000 2.6000 3.4000 4.2000 5.0000
推荐答案
你可以做的第一件事是切换到使用 std::generate
或 std::generate_n
而不是 for 循环.generate
版本可能看起来像
The first thing you could go is switch to using std::generate
or std::generate_n
instead of a for loop. The generate
version could look like
int main()
{
float a = 1.132;
std::vector<float> v(100);
std::generate(v.begin(), v.end(), [n = 0, &a]() mutable { return n++ * a; });
}
另一种选择是创建一个迭代器,它会在您迭代时生成值.这样做的好处是您不需要使用任何默认构造值来初始化 v
(这可能/代价昂贵).然后使用向量范围构造函数,它将初始化所有元素.只要迭代器遵守前向迭代器的要求,向量就会计算出所需的空间(如果不是随机访问会导致全迭代),分配,然后初始化(全迭代).这对于双迭代来说可能很昂贵,因此它可能不会比生成情况更快,而且可能会更慢(因为零初始化非常快).
Another option is to create an iterator that will generate the value as you iterate it. This has the advantage that you do not need to initialize v
with any default constructed valued (this can be/is expensive). Then you use the vectors range constructor and it will initialize all of the elements. As long as the iterator abides by the forward iterator requirements then the vector will figure out the space needed (which if it is not random access causes a full iteration), allocate, and then initialize(full iteration). This could be expensive with the double iteration so it might not be any faster and could be slower then the generate case (since zero initializing is pretty fast).
这篇关于用线性增加的值填充向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!