gpt4 book ai didi

c++ - 任何令人满意的迭代器递归来替换类型为$ a [i] = b [i] * c [i] $的for循环

转载 作者:行者123 更新时间:2023-12-02 09:47:27 24 4
gpt4 key购买 nike

我试图使我的代码更具可读性,并避免使用索引进行循环,因为迭代器更加灵活。
虚拟数据

time        a          b
0 6 7
0.5 2 1.5
1.0 9 3
1.5 0 2
现在为了计算 vector c我通常会介绍for循环
vector<double> c;

for (int i = 0; i < a.size(); i++)
{
c[i] = a[i] * b[i];
}
为了避免混淆索引并使代码更具可读性,我想使用迭代器。
到目前为止,我的尝试:
vector<double> c;

vector<double>::iterator it_a, it_b;

for (it_a = a.begin(); it_a != a.end(); it_a++)
{
for (it_b = b.begin(); it_b != b.end(); it_b++)
{
if (it_b == it_a)
{
c.push_back((it_a *)*(it_b *));
}
}
}
我很确定这是错误的。有任何想法吗?

最佳答案

如果要提高可读性,请使用STL算法:

// Initialise result vector
vector<double> c(a.size());

// Iterate through a & b and push the result of the binary func into c
std::transform(a.cbegin(), a.cend(),
b.cbegin(),
c.begin(),
std::multiplies<>{});

Godbolt link

关于c++ - 任何令人满意的迭代器递归来替换类型为$ a [i] = b [i] * c [i] $的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64386016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com