Multiply vector elements by a scalar value using STL

Viewed 80954

Hi I want to (multiply,add,etc) vector by scalar value for example myv1 * 3 , I know I can do a function with a forloop , but is there a way of doing this using STL function? Something like the {Algorithm.h :: transform function }?

6 Answers

Modern C++ solution for your question.

#include <algorithm>
#include <vector>

std::vector<double> myarray;
double myconstant{3.3};
std::transform(myarray.begin(), myarray.end(), myarray.begin(), [&myconstant](auto& c){return c*myconstant;});

If you had to store the results in a new vector, then you could use the std::transform() from the <algorithm> header:

#include <algorithm>
#include <vector>

int main() {
    const double scale = 2;
    std::vector<double> vec_input{1, 2, 3};
    std::vector<double> vec_output(3); // a vector of 3 elements, Initialized to zero
    // ~~~
    std::transform(vec_input.begin(), vec_input.end(), vec_output.begin(),
                   [&scale](double element) { return element *= scale; });
    // ~~~
    return 0;
}

So, what we are saying here is,

  • take the values (elements) of vec_input starting from the beginning (vec_input.begin()) to the end (vec_input.begin()),
    • essentially, with the first two arguments, you specify a range of elements ([beginning, end)) to transform, range
  • pass each element to the last argument, lambda expression,
  • take the output of lambda expression and put it in the vec_output starting from the beginning (vec_output.begin()).
    • the third argument is to specify the beginning of the destination vector.

The lambda expression

  • captures the value of scale factor ([&scale]) from outside by reference,
  • takes as its input a vector element of type double (passed to it by std::transform())
  • in the body of the function, it returns the final result,
    • which, as I mentioned above, will be consequently stored in the vec_input.

Final note: Although unnecessary, you could pass lambda expression per below:

[&scale](double element) -> double { return element *= scale; }

It explicitly states that the output of the lambda expression is a double. However, we can omit that, because the compiler, in this case, can deduce the return type by itself.

Related