How to take sum over vector after some operation in C++ [closed]

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

  1. construct new array for (vector2 – constant)**2, then new array for vector1 * (vector2 – constant)**2, then use std::accumulate
  2. 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 ?

  • 2

    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?

    – 

Leave a Comment