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.
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.
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.
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.
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.
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.
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;
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