2016-03-03 155 views
0

我有兩個整數數組比較兩個整數數組的元素在C++

#include<iostream> 
using namespace std; 
int comparetwoarrays(int array1[], int array2[], int ARRAY_SIZE1, int ARRAY_SIZE2) 

int main() 
{ 
    int const ARRAY_SIZE = 500; 
    int const ARRAY_SIZE = 10; 
    int array1[ARRAY_SIZE]; 
    int array2[ARRAY_SIZE2]; 
    comparetwoarrays(array1, array2, ARRAY_SIZE1, ARRAYSIZE2) 
} 

int comparetwoarrays(int array1[], int array2[], int ARRAY_SIZE1, int ARRAY_SIZE2) 
{ 
    int holdsAlike[10] = {0}; 
    for(int g = 0; g < ARRAY_SIZE2; g++) 
    { 
     for (int t = 0; t < ARRAY_SIZE2; t++) 
     { 
      if (array2[g] == array1[t]) 
      { 
       holdsAlike[g] = array2[g]; 
       cout<<holdsAlike[g]; 
      } 
      for(int w = 0; w < ARRAY_SIZE2; w++) 
      { 
       if(holdsAlike[w] != 0) 
       cout<<holdsAlike[w]; 
      } 
     } 
    } 

欲兩個陣列的元素進行比較,並打印出值和所述元素的索引。不知道如何去做到這一點。任何洞察力將不勝感激。

+0

你有ARRAY_SIZE'的'兩個定義。我想其中任何一個應該是'ARRAY_SIZE2'。 – MikeCAT

+0

是的,我試圖比較較大陣列的前10個元素與較小陣列 – programmerintraining

+0

這看起來像作業。你的具體問題是什麼? – barq

回答

0

代碼你想要的。這可能是這樣的:

#include <iostream> 

using std::cout; 

int comparetwoarrays(const int array1[], const int array2[], int array_size1, int array_size2); 

int main() 
{ 
    int const ARRAY_SIZE1 = 500; 
    int const ARRAY_SIZE2 = 10; 
    int array1[ARRAY_SIZE1] = {0}; 
    int array2[ARRAY_SIZE2] = {0}; 

    // set values to the arrays 

    comparetwoarrays(array1, array2, 10, ARRAY_SIZE2); 
} 

void comparetwoarrays(const int array1[], const int array2[], int array_size1, int array_size2) 
{ 
    for(int g = 0; g < array_size2; g++) 
    { 
     for (int t = 0; t < array_size1; t++) 
     { 
      if (array2[g] == array1[t]) 
      { 
       if (g == t) 
       { 
        cout << "got \"" << array2[g] << "\" at index " << g << "\n"; 
       } 
       else 
       { 
        cout << "got value = " << array2[g] << ", index on array2 = " << g <<", index on array1 = " << t << "\n"; 
       } 
      } 
     } 
    } 
} 

如果你只想打印元素既指標和價值相匹配:

void comparetwoarrays(const int array1[], const int array2[], int array_size1, int array_size2) 
{ 
    for(int g = 0; g < array_size1 && g < array_size2; g++) 
    { 
     if (array2[g] == array1[g]) 
     { 
      cout << "got \"" << array2[g] << "\" at index " << g << "\n"; 
     } 
    } 
} 
+0

我會試試看...... btw謝謝你的幫助 – programmerintraining

+0

對於每個array1元素,數組2將其索引更改爲0 - 9,直到它的數組1達到499 ... .-。 – programmerintraining

+0

添加了比較前10個元素的代碼。 – MikeCAT