Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Multiplying elements in a vector

Tags:

c++

c++11

I have been looking for a more optimal solution to the following and I cannot seem to find one.

Let's say I have a vector:

std::vector<double> vars = {1, 2, 3}

I want to perform 1 * 2 * 3 I know that I can do the following:

int multi = 1;

for(int i = 0; (i < vars.size()-1); i++)
{
    multi *= vars[i];
}

But, is there a more "C++11" way to do this? I really wanted to do this using lambda and so that I can calculate the multiply (product) of the vector without having another function inside the class, I'd rather have it calculated inside the function.

like image 393
Phorce Avatar asked Mar 19 '15 13:03

Phorce


People also ask

How do you multiply vector elements?

Dot product – also known as the "scalar product", a binary operation that takes two vectors and returns a scalar quantity. The dot product of two vectors can be defined as the product of the magnitudes of the two vectors and the cosine of the angle between the two vectors.

How do you multiply elements in a vector 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.

How do you find the product of all elements in a vector?

Description. B = prod( A ) returns the product of the array elements of A . If A is a vector, then prod(A) returns the product of the elements.

What happens when you multiply vector?

When two vectors are multiplied with each other and the multiplication is also a vector quantity, then the resultant vector is called the cross product of two vectors or the vector product. The resultant vector is perpendicular to the plane containing the two given vectors.


2 Answers

Yes, as usual, there is an algorithm (though this one's in <numeric>), std::accumulate (live example):

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.

In C++14, you can replace std::multiplies<double> with std::multiplies<>, whose operator() is templated and will figure out the type. Based on what I've seen with Eric Niebler's Ranges proposal, it could possibly later look like vars | accumulate(1, std::multiplies<>()), but take that with a grain of salt.

like image 166
chris Avatar answered Sep 22 '22 17:09

chris


You can use a ranged based for loop like:

std::vector<double> vars = {1, 2, 3}
int multi = 1;

for (const auto& e: vars)
    multi *= e;
like image 32
NathanOliver Avatar answered Sep 20 '22 17:09

NathanOliver