2017-04-30 19 views
-2

2つの配列の異なる単語を1つの配列にリンクするユニオン( "U")演算を作成しようとしていますが、動作しません。誰でも助けてくれますか?ありがとうございました。2つのC++配列の結合を計算する方法

これは私の連合機能である:

#define N 19 

void CalcularUnion (tConjunto X, tConjunto Y, tConjunto* Z) 
{ 
    int i, j, k; 
    strcpy((*Z).Nombre, X.Nombre); 
    strcat((*Z).Nombre, "U"); 
    strcat((*Z).Nombre, Y.Nombre); 

    for (i=0; i<N; i++) 
    { 
     strcpy((*Z).Elementos[i], " "); 
    } 

    for(i=0; i<N; i++) 
    { 
     if(strlen(X.Elementos[i]) != 0) 
     { 
      strcpy((*Z).Elementos[i], X.Elementos[i]); 
     } 

     else 
     { 
      break; 
     } 
    } 

    for(j=0; j<N; j++) 
    { 
     if(strlen(Y.Elementos[j]) != 0) 
     {   
      for(k=0; k<N; k++) 
      { 
       if(strcmp(Y.Elementos[j], X.Elementos[k]) == 0) 
       { 
        break; 
       } 

       else 
       { 
        strcpy((*Z).Elementos[i], Y.Elementos[j]); 
       } 
      } 
     } 
    } 

    ImprimirConjunto(*Z); //To print the result 
} 

tConjunto Xは含む配列です:Andalucia, Catalunia, Canarias tConjunto Yは含む配列です:Extremadura, Asturias tConjunto Zは結果でなければなりません。

この場合、結果は次のようになります。tConjunto Z --> Andalucia, Catalunia, Canarias, Extremadura, Asturias.ただし、最初の配列(X)の単語の1つが2番目の単語に含まれているかどうかをチェックし、省略します。

誰でも手伝ってもらえますか? ありがとうございました!

+6

'std :: string'を使用してください。後でありがとう。 –

+0

'tConjunto'の定義を表示できますか?特に' Elementos'が(ユニット化された) 'char *'ポインタであるか、または割り当てを必要としないcharの配列であれば可能です。ところで、あなたがEmerald Weaponの勧告を適用することに決めたなら、あなたは彼に感謝することができます。もう答えは必要ありません;-) – Christophe

+0

また、参照で 'X'と' Y'を渡すべきです。文字列の大きな配列はコピーされません。より良いperf: 'void CalcularUnion(tConjunto&X、tConjunto&Y、tConjunto * Z)' – selbie

答えて

1

C++を使用しているため、std::stringstd::unordered_setを使用できます。 XYの各文字列をセットに挿入します。重複は暗黙的に除外されます。次に、セット内のユニークなアイテムを列挙し、Z構造体にコピーします。

#include <unordered_set> 

std::unordered_set<std::string> items; 

// copy all the strings from X and Y into a set 
// duplicates will not get inserted into this collection 
for (int i = 0; i < N; i++) 
{ 
    std::string str; 
    str = X.Elementos[i]; 
    items.insert(str); 
    str = Y.Elementos[i]; 
    items.insert(str); 
} 

// copy all the strings back into Z 
int j = 0; 
for (auto itor = items.begin(); itor != items.end(); itor++) 
{ 
    std::string str = *itor; 
    if (!str.empty()) 
    { 
     // copy to your Z structure 
     strcpy(Z->Elementos[j], str.c_str()); 
     j++; 
     if (j >= N) // I'm assuming that Elementos has a max capacity of N items, you can change as appropriate 
     { 
      break; 
     } 
    } 
} 
関連する問題