2017-09-15 10 views
0

2つのベクトルの内積を計算する書き込みC++プログラムを試しています。ベクトルaとbでは、非ゼロ要素のみが構造体の配列に格納されます。私は、構造体の配列にベクトルを正しく読み込むことができないと思います。 アドバイスをお願いします。 は、事前にありがとう0以外のベクトルメンバーを配列に読み込んでドットプロダクトを出力する

#include <iostream> 
#include <vector> 
using namespace std; 

const int n=10; /* vector size limit */ 
struct element { 
int x; /* original index of non-zero array element */ 
int val ; /* integer non-zero value at index x */ 
}; 
element row[n]; 
element col[n]; 

int i; 
vector<int> a={0,0,7,0,5,0,0,8,0,4,-1}; 
vector<int> b={0,0,0,5,6,0,0,0,0,5,-1}; 

void generate_row_and_col() 
{ 
    for (i=0; i<=n; i++) 
    { 
     if(a[i]=!0) 
     { 
      row[i].x=i; 
      row[i].val=a[i]; 
     } 
    } 
    for (i=0; i<=n; i++) 
    { 
     if(b[i]!=0) 
     { 
      col[i].x=i; 
      col[i].val=b[i]; 
     } 
    } 
} 
int dotproduct() 
{ 
/* calculate the dot product of row and col output the result*/ 
int i=0; 
int j=0; 
int product=0; 
while(row[i].x!=-1 && col[j].x!=-1) 
{ 
    if(row[i].x == col[j].x) 
    { 
     product=product+row[i].val*col[j].val; 
     i++; 
     j++; 
    } 
    else if(row[i].x<col[j].x) 
    { 
     i++; 
    } 
    else 
    { 
     j++; 
    } 
} 
return product; 
} 
int main() 
{ 
generate_row_and_col() ; 
int r; 
r=dotproduct(); 
cout<<"result="<<r<<endl; 
return 0; 
} 
+1

のような* - [STD :: inner_product](HTTP ://en.cppreference.com/w/cpp/algorithm/inner_product)が動作します。実際には、これは無関係な配列を使わない3行のプログラムです。これには 'std :: stable_partition'を呼び出すだけでゼロ要素を取り除くことが含まれます。 – PaulMcKenzie

答えて

0

あなたdotproduct()でなければなりません与えられた二つのベクトルの内積を計算するプログラム++ * Iが書き込みCをしようとしています

int dotproduct() 
{ 
    /* calculate the dot product of row and col output the result*/ 
    int i=0; 
    int j=0; 
    int product=0; 
    while(row[i].val != -1) 
    { 
     j = 0; 
     while(col[j].val != -1) 
     { 
      if(row[i].x == col[j].x) 
      { 
       product=product+row[i].val*col[j].val; 
       break; 
      } 
      j++; 
     } 
     i++; 
    } 
    return product; 
} 
+0

私は結果として50を取得するはずですが、この場合私は102を取得しています – mwater07

+0

Generator関数にない場合、私のdotproduct関数に問題があると思います – mwater07

関連する問題