Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply vector elements by a scalar value using STL

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 }?

like image 793
Ismail Marmoush Avatar asked Oct 07 '10 19:10

Ismail Marmoush


People also ask

How do you multiply a vector by a scalar?

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 .

How do you multiply a 3d vector by a scalar?

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.

Can you multiply a vector by a scalar C++?

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.

How do you multiply a vector element in C++?

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.


2 Answers

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>  
like image 90
Oliver Charlesworth Avatar answered Oct 11 '22 16:10

Oliver Charlesworth


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)

like image 45
Chris Jester-Young Avatar answered Oct 11 '22 15:10

Chris Jester-Young