Question

I´m sure there´s a clever one-liner using the C++ stl generic algorithms for implementing the dot product of the elements in any ordered container, such as a vector or list. I just don´t seem to remember it!

The fancy implementation would be:

template <class containerT>
typename containerT::value_type dot_product (const containerT& left, const containerT& right)
{
   assert(left.size()==right.size());
   containerT::value_type result = 0;
   for (containerT::const_iterator l_it = left.begin(), r_it = right.begin();
        l_it != left.end(); ++r_it,++l_it)
   {
      result += (*l_it) * (*r_it);
   }
   return result; 
}

I think that i´m reinventing the wheel and that there´s a more clever way to do this.

Was it helpful?

Solution

See std::inner_product from <numeric>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top