Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Product

 

Math code snippet to calculate the product of the elements of a std::vector.

 

Product can be programmed multiple ways:

 

 

 

 

 

Product using algorithms

 

#include <vector>

int Product(const std::vector<int>& v)
{
  const int sz = v.size();
  const int product = 1;
  for (int i=0; i!=sz; ++i)
  {
    product*=v[i];
  }
  return product;
}

 

 

 

 

 

Product using a for-loop

 

#include <vector>
#include <algorithm
#include <numeric>

int Product(const std::vector<int>& v)
{
  return std::accumulate(v.begin(),v.end(),1,std::multiplies<int>());
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict