Just use std::inner_product:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <numeric>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> v1,v2;
generate_n( back_inserter(v1), 256, rand );
generate_n( back_inserter(v2), v1.size(), rand );
cout << inner_product( v1.begin(), v1.end(), v2.begin(), 0 ) << endl;
}
Yes, that’s a good solution. But I don’t want to use any methods provided in numeric.h.
Just define your own dot_product:
template<typename InputIterator1,typename InputIterator2,typename ValueType>
ValueType dot_product( InputIterator1 first, InputIterator1 last, InputIterator2 another, ValueType init)
{
while(first!=last)
{
init += (*first) * (*another) ;
++first;
++another;
}
return init;
}
1
solved Get the dot product of two vectors by functors and STL algorithms