2016-04-05 80 views
-2

所以我的問題是,我需要比較兩個數組。像這樣比較它們,如果數組1有值 - 1 2 3並且數組2具有值3 2 1,程序就會發現它是相等的。現在,只有在數組1的值 - 1 2 3和數組2的值 - 1 2 3的情況下,我才讓它工作,然後它發現數組相等,但是我需要搜索具有相似值的數組,但在同一個地方沒有興奮。 現在我使用下面的代碼來搜索數組中的相等值。但它不會工作,如果你需要搜索相同的值,但在不同的位置。希望你們大多數人都能理解我的問題。對於英語不好,對不起,我的母語不好。我如何比較兩個數組?

int skaitluParbaude(int loterija[], int speletajs[]) 
{ 
int match = 0; 

for (int x = 0; x < SKAITS; ++x) 
{ 
    if (loterija[x] == speletajs[x]) 
     match = match + 1; 

} 
return match; 
} 
+1

排序陣列然後比較 –

+0

可能想使用一個標準庫容器的,而不是圍繞C風格的數組一樣,吊索。 – tadman

+1

有幾個問題需要回答:1)這些數組可以在搜索之前排序嗎? 2)如果不允許對數組進行排序,您可以使用中間數據結構(即'set')來計算兩個數組是否具有相等的值? – PaulMcKenzie

回答

0

使用如果工作{1,2,3}{1,2,3}相比,您所使用的具體方法。

但:在開始比較之前對兩個數組進行排序。這是圈套,這裏是你如何排序的數組:

std::sort(YourArray.begin(), YourArray.end()); 
0

排序的兩個陣列並應用方法如下:

int skaitluParbaude(int loterija[], int speletajs[]) 
{ 
int match = 0; 

sort(loterija,loterija + x); 
sort(speletajs,speletajs + x); 


for (int x = 0; x < SKAITS; ++x) 
{ 
    if (loterija[x] == speletajs[x]) 
     match = match + 1; 

} 
return match; 
} 

這包括<algorithm>的頭文件。而x是數組的大小。

1

有兩種方法,我能想到的:

  1. 排序比較之前的陣列。一旦排序,您可以比較從索引0開始的元素。如果發現不匹配,則數組不會相等。

  2. 從陣列創建兩個std::set s並使用std::set::operator==

    std::set<int> s1(std::begin(array1), std::end(array1)); 
    std::set<int> s2(std::begin(array2), std::end(array2)); 
    s1 == s2; 
    
0

如果你知道數組的大小,事先你可以使用散列,與陣列的最大元素替換INT_MAX。

bool similar(int loterija[], int speletajs[]){ 

    int arr[INT_MAX], flag = 0; 
    std::fill(begin(arr),end(arr),0); 

    for (int x = 0; x < SKAITS; ++x) 
     arr[loterija[x]] = 1; 
    for (int x = 0; x < SKAITS; ++x) 
     if(arr[speletajs[x]] != 1) { 
      flag = 1; 
      break; 
     } 
    if(flag == 0) 
     return true; 
    else 
     return false; 
}