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

标签 c++ loops vector indexing iterator

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

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/

相关文章:

c++ - 我应该选择什么同步方案来避免实时 C++/MFC 应用程序上的死锁?

c++ - 避免 C++ 循环中复杂对象的最小范围效率低下的技术?

c - 平衡的表达

python - 如何组合一维数组来创建一个新数组

java - Android 中的 Animate Drawable 图标 - ClassCastException VectorDrawable 无法转换为 Animatable

c++ - 文件系统路径字符串方法返回 mixed\and/

c++ - 解释 Valgrind 的 trace-malloc 输出

c++ - Variadic 模板候选者不匹配

php - 将mysql while循环数据保存到数组中,然后保存到数据库中

c++ Vector push_back移动新元素