How to calculate inner product (sum of products) of two vectors in C++

1 Answer

0 votes
#include <iostream>  
#include <numeric>
#include <vector> 

using std::vector;
using std::cout;
using std::endl;

int main()
{
	vector<int> v1{ 0, 1, 2, 3, 4 } , v2{ 5, 4, 2, 3, 1 };

	// (0*5)+(1*4)+(2*2)+(3*3)+(4*1) = 0 + 4 + 4 + 9 + 4 = 21
	int ip = inner_product(v1.begin(), v1.end(), v2.begin(), 0);

	cout << ip << endl;

	return 0;
}

/*
run:

21

*/

 



answered Apr 24, 2018 by avibootz
...