2016-12-31 29 views
0

我有兩個數組,我想計算兩個數組之間有多少個元素相同。 我嘗試了很多次,但輸出不正確。正確的應該是6乘以 ,但代碼中的輸出是4次。C++如何打印2個數組中有多少元素重複?

注:如果s1"ss"s2"ss",是結果2

這裏是我的代碼:

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

int main() { 
    char s1[] = "FOOBART"; 
    char s2[] = "BFORATO"; 
    int flag=0; 

    for(int i=0, j=0; i < sizeof(s1) && j < sizeof(s2);) { 
     if(s1[i] == s2[j]) {    
      flag++; 
      i++; 
      j++; 
     } else if(s1[i] < s2[j]) { 
      i++; 
     } else { 
      j++; 
     } 
    } 
    cout << flag; 
} 
+2

定義 「是相同的」。有很多方法可以解釋這一點。 –

+0

你需要計數匹配的_different_字符還是全部?如果's1'是「ss」,'s2'是「ss」,結果是1還是2? –

+0

您當前的程序輸出4,不是預期的6也不是意想不到的8:[Demo](http://ideone.com/N6edoh)。 – Jarod42

回答

0

S1的所有元素都存在兩個字符串所以輸出將等於到s1的長度。下面是正確的代碼

#include <iostream> 
using namespace std; 

int main() { 
    char s1[] = "FOOBART"; 
    char s2[] = "BFORATO"; 
    int count=0; 
    for (int i=0; i<sizeof(s1)-1; i++) { 
     for (int j=0; j<sizeof(s2)-1; j++) { 
      if (s1[i]==s2[j]) { 
       count++; 
       break; 
      } 
     } 
    } 

    cout<<count<<endl; 
} 

希望這將使用STL的算法幫助你

0

解決方案:

#include <iostream> 
#include <algorithm> 
#include <string> 
int main() 
{ 
    const std::string s1 = "FOOBART"; 
    std::string s2 = "BFORATO"; 

    int count = 0; 
    auto beg = begin(s2); 
    for(auto& elm : s1) 
    { 
     auto x = find(beg, end(s2), elm); 
     if(x != end(s2)) 
     { 
      *x = *beg;//get rid of elment and reduce the range of search. 
      ++beg; 
      ++count; 
     } 

    } 
    std::cout << count; 
    return 0; 
} 
相關問題