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 }?
To multiply a vector by a scalar, multiply each component by the scalar. If →u=⟨u1,u2⟩ has a magnitude |→u| and direction d , then n→u=n⟨u1,u2⟩=⟨nu1,nu2⟩ where n is a positive real number, the magnitude is |n→u| , and its direction is d .
To multiply any vector by a scalar, we multiply each of the individual components by that scalar. If ⃑ 𝐴 = ( 𝑥 , 𝑦 , 𝑧 ) , then 𝑘 ⃑ 𝐴 = ( 𝑘 𝑥 , 𝑘 𝑦 , 𝑘 𝑧 ) . The magnitude of a vector is its length and can be calculated by adapting the Pythagorean theorem in three dimensions.
In this article, we will discuss how to Multiply vector by a Scalar in C++. Multiplying Vector by a Scalar value means multiplying each element of the vector by the same constant value. We can perform vector scalar multiplication in many ways.
using std::begin; using std::end; auto multi = std::accumulate(begin(vars), end(vars), 1, std::multiplies<double>()); std::multiplies is in <functional> , too. By default, std::accumulate uses std::plus , which adds two values given to operator() . std::multiplies is a functor that multiplies them instead.
Yes, using std::transform
:
std::transform(myv1.begin(), myv1.end(), myv1.begin(), std::bind(std::multiplies<T>(), std::placeholders::_1, 3));
Before C++17 you could use std::bind1st()
, which was deprecated in C++11.
std::transform(myv1.begin(), myv1.end(), myv1.begin(), std::bind1st(std::multiplies<T>(), 3));
For the placeholders;
#include <functional>
If you can use a valarray
instead of a vector
, it has builtin operators for doing a scalar multiplication.
v *= 3;
If you have to use a vector
, you can indeed use transform
to do the job:
transform(v.begin(), v.end(), v.begin(), _1 * 3);
(assuming you have something similar to Boost.Lambda that allows you to easily create anonymous function objects like _1 * 3
:-P)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With