Reputation: 175
So I have two vectors:
vector<int> v1(size);
vector<int> v2(size);
and what I want is to calculate A[0]*B[0] - A[1]*B[1] - A[2]*B[2] - ... - A[n-1]*B[n-1]
. I've tried the following
#include <iostream>
#include <vector>
using namespace std;
int main()
{
size_t size = 4;
vector<int> product; int i;
vector<int> v1(size);
vector<int> v2(size);
v1[0] = 2; v2[0] = 4;
v1[1] = 5; v2[1] = 1;
v1[2] = 9; v2[2] = 6;
v1[3] = 3; v2[3] = 7;
for(i=1;i < v1.size();++i){
product.push_back(v1[i]*v2[i]);
}
for(vector<int>::const_iterator i = product.begin(); i != product.end(); ++i)
std::cout << *i << ' ';
return 0;
}
However, this would return 5 54 21
as of v1[1]*v2[1], v1[2]*v2[2] and v1[3]*v2[3]
and I want to subtract them from each other: 5-54-21
.
Upvotes: 0
Views: 170
Reputation: 2745
What about
vector<int> v1{2,5,9,3};
vector<int> v2{4,1,6,7};
int result = std::inner_product(++v1.beginn(),v1.end(),++v2.begin(),v1[0]*v2[0],std::minus<>,std::multiplies<>);
(with C++14)
int result = std::inner_product(++v1.beginn(),v1.end(),++v2.begin(),v1[0]*v2[0],std::minus<int>,std::multiplies<int>);
(with C++98)
Upvotes: 1
Reputation: 35314
Firstly, in your formula, the first product must be added (IOW is positive), while the remaining are subtracted. So you must treat the two cases differently.
Secondly, you can perform the calculation easily by computing an ongoing result, starting from zero:
int result = 0;
if (size >= 1) {
result += v1[0]*v2[0];
for (int i = 1; i < size; ++i)
result -= v1[i]*v2[i];
}
std::cout << result << std::endl;
Upvotes: 2