Math code snippet to calculate the product of the elements of a std::vector.
Product can be programmed multiple ways:
- Using algorithms (preferred)
- Using a for-loop
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; }
#include <vector> #include <algorithm #include <numeric> int Product(const std::vector<int>& v) { return std::accumulate(v.begin(),v.end(),1,std::multiplies<int>()); }