How to the write the following python most efficiently in c++ ?
sum(vector1 * (vector2 – constant)**2)
vector1 and 2 are of same length, constant is just scalar.
I can think of
- construct new array for (vector2 – constant)**2, then new array for vector1 * (vector2 – constant)**2, then use std::accumulate
- use for loop to calculate what’s inside parenthesis for each element, then just add to a sum
Is there some (approximate) one liner in C++ like this in python ?
The standard ranges library might help (if your compiler and standard library are new enough). Or the range library which was the base for the standard.
can you give an example code using ranges?
This worked for me:
auto result{ accumulate(zip(vector1, vector2) | transform([constant](auto x) { auto&& [aa, bb] = x; return aa * sqr(bb - constant); }), 0.0) };
How do you subtract a scalar from a vector?