I have to apply the same operation to two or more different vectors.
An example of the function is below, it is very basic (multiplying a vector by a scalar in place).
I have other functions like this but this is an example
fn multiply_vector_in_place(inp: &mut [i32], scalar: i32){
for k in inp.iter_mut(){
*k *= scalar;
}
}
Now I want to perform the same operation to two vectors v1, v2. For performance reasons I want to avoid looping over the vectors twice, so I do the following:
fn multiply_vectors_in_place(inp: &mut [i32], scalar: i32, inp2; &mut [i32], scalar2: i32){
for k1,k2 in inp.iter_mut().zip(inp2.iter_mut()){
*k1 *= scalar1;
*k2 *= scalar2;
}
}
This works, but obviously this code very ugly and not general and not reusable.
Is there a clear, or more idiomatic way to do this?
Is there any benefit in combining loops this way for performance reasons? I am writing performance critical code.
1 post - 1 participant