Dot Product

Hello I am trying to do an assignment that dot products two vectors while passing the following tests.
but it will not pass my tests
here is my code for dot product

double Vec::operator*( Vec& a) {
double sum=0;
//Vec a;
a=NULL;
a.setSize(mySize);
if(mySize==a.getSize()){

for(unsigned i=0;i<a.getSize()-1;i++){
sum+=a.myArray[i]*myArray[i];

}
}else{
throw invalid_argument("The size exception");
} cout<<"print"<<endl;

return sum;


}


here is my test

void VecTester::testDotProduct() const {
cout << "Testing *... " << flush;
Vec v1(3);
Vec v2(3);
v1.setItem(0, 1);
v1.setItem(1, 2);
v1.setItem(2, 3);
v2.setItem(0, 2);
v2.setItem(1, 4);
v2.setItem(2, 6);
Vec saveV1 = v1; // for test 2 below
double product = v1 * v2;
assert( product == 28 );
cout << " 1 " << flush;
// dot product should not change the left operand
assert( v1.getItem(0) == saveV1.getItem(0) );
assert( v1.getItem(1) == saveV1.getItem(1) );
assert( v1.getItem(2) == saveV1.getItem(2) );
cout << " 2 " << flush;
// empty
Vec v4, v5;
product = v4 * v5;
assert( product == 0 );
cout << " 3 " << flush;
// different sizes
try {
product = v2 * v4;
cerr << "v2 * v4 succeeded for Vecs of different sizes";
exit(1);
} catch (invalid_argument&) {
cout << " 4 " << flush;
}
cout << "Passed!" << endl;
}
Passing a non-const reference to an implementation of a mathematical binary operator is suspect. Why do you need this?
Please use code tags so we can refer to specific line numbers. Here is your dot-product operator tagged and indented. See my comments below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
double Vec::operator*( Vec& a) {
    double sum=0;
    //Vec a;
    a=NULL;
    a.setSize(mySize);
    if(mySize==a.getSize()){

	for(unsigned i=0;i<a.getSize()-1;i++){
	    sum+=a.myArray[i]*myArray[i];

	}
    }else{
	throw invalid_argument("The size exception");
    } cout<<"print"<<endl;

    return sum;
}

Line 4 appears to blow away the input vector.
Line 5: If it somehow survived line 4, then line 5 changes its size.
Line 6: Given line 5, when would a.getSize() NOT equal mySize?

In your test code, rather than calling assert(), I suggest that you print the product and the expected value. If the result is wrong, then it will be helpful to know what the incorrect value is.
You'd use a dot product thing like this:
 
double c = dot_product(a, b);
So it's not a member of a Vector, but a free standing function. I'd expect it to look something like:
1
2
3
4
double func(const Vec& a, const Vec& b)
{
	//....
}

Having said that, if you change the signature of that method to:
 
double Vec::operator*(const Vec& a) const
the language will catch your errors.

BTW, there's a standard library algorithm that'll do dot product. http://en.cppreference.com/w/cpp/algorithm/inner_product
thanks I figured it out
Topic archived. No new replies allowed.