Dot product in C ++ using common algorithms
I'm sure there is a clever one-liner using generic C ++ stl algorithms to implement the dot product of elements in any ordered container like a vector or a list. I just don't seem to remember it!
Intended implementation:
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 I am reinventing the wheel and that there is a smarter way to do it.
+1
source to share