2017-09-15 1 views
0

주어진 두 벡터의 내적을 계산하는 쓰기 C++ 프로그램을 시도하고 있습니다. 벡터에서 a 및 b 만 0이 아닌 요소는 구조체 배열에 저장됩니다. 나는 구조의 배열로 벡터를 제대로 읽을 수 없다고 생각합니다. 상담하십시오. 가 사전에 감사배열에 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

같은 * - [표준 : inner_product] (HTTP : //en.cppreference.com/w/cpp/algorithm/inner_product)이 작동합니다. 사실, 이것은 외계 배열을 사용하지 않는 3 행 프로그램이며, 단순히'std :: stable_partition'을 호출하여 제로 요소를 제거하는 것을 포함합니다. – PaulMcKenzie

답변

0

귀하의 dotproduct()이어야 주어진 두 벡터의 내적을 계산 프로그램 ++ * 내가 쓰기 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