Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::multiplies on vector containing 0's

Tags:

c++11

stl

vector

I have a vector, containing the following values

0 0 1 1

And my aim is to multiply this vector and return a double, for this, I am using the std::accumulate and std::multiplies but I have noticed a problem, because there is 0's contained the returning value is always 0. For example (0 * 0 * 1 * 1) = 0

Is it possible to do use std::multiplies to ignore all values that are 0's? Technically, in this part, I am just after the result of: (1 * 1) for example.

I am using:

std::accumulate(diag1.begin(), diag1.end(), 1, std::multiplies<double>());

Where diag1 contains the values inside this example.

like image 939
Phorce Avatar asked Nov 18 '25 16:11

Phorce


1 Answers

You can use C++11 and lambda expressions as suggested by Piotr Skotnicki in the comments, or you can utilize the pre-11 approach (verbosity intended):

struct F 
{ 
   template<class T>
   T operator()(const T &a, const T &b) const
   {
      if (a != 0 && b != 0)
         return a*b;
      else 
      {
          if (a != 0) return a;
          else if (b != 0) return b;
          else return 1;
       }
    }
};
double res = std::accumulate(diag1.begin(), diag1.end(), 1.0d, F());

But be careful with the comparison against 0. The 0 represented as a double may not be the mathematical 0. Furthermore, the multiplication may not be necessarily correct because of the way the floating point numbers are represented in binary, by computers.

like image 122
asalic Avatar answered Nov 21 '25 10:11

asalic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!