2017-02-18 12 views
0

これは私が書かれているテキストファイルです:文字列の配列から隣接する重複文字列を削除しますか?

this is the first line 
this is the first line 
this is the second line 
this is the second line 
this is the second line 
this is the third line 
this is the first line 

私は、隣接する重複した文字列を削除しようとしていますので、出力は次のようになります。

this is the first line 
this is the second line 
this is the third line 
this is the first line 

これは私がこれまでに書かれたものです。

for(int i = 0; i < n; i++) 
getline(infile,arr[i]); 

for(int i=0; i<n; i++) 
{ 
     int j = i+1; 
     if(arr[i] == arr[j]) 
     { 
       for(int k = i; k<n; k++) 
       arr[k] = arr[k+1]; 
       n--; 
     } 
} 

これは私が手に出力されます:

this is the first line 
this is the second line 
this is the second line 
this is the third line 
this is the first line 

これを修正するにはどうすればよいですか? P.S .:これを繰り返して解決しなければならないので、私はこのようにしています。

+0

「arr」のタイプは何ですか。 –

+0

あなたはSTLを知っていますか? –

+2

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

答えて

2

あなたが同じ行の2つの以上の重複を持っているとき、あなたの問題が起こります。あなたの場合、これは問題を引き起こします。

this is the second line 
this is the second line 
this is the second line 

問題は、次の要素で1回しか重複しないことです。

例: あなたがライン1 4行、2、3が重複しているを持っている場合は、になります。

  1. は2と1を比較して、2を削除し、1に配列を圧縮し、3

  2. 代わりに3と1を比較すると、あなたは4で(間違った)3を比較するために、スキップでしょう

あなたのソリューションを固定するために、あなたはincのないことを確認する必要があります次の要素i+1と一致しなくなるまでiを返します。

i = 0; 
while (i < n) 
{ 
    int j = i+1; 
    if(arr[i] == arr[j]) 
    { 
     for(int k = i; k<n; k++) 
     { 
      arr[k] = arr[k+1]; 
     } 
     n--; 
    } 
    else 
    { 
     i++; 
    } 
} 
+0

ありがとう、そんなにそうそうそうとてもそんなに!!!! :) :) :) – Stardust1992

0

std::uniqueを使用してください。

auto end = std::unique(std::begin(arr), std::end(arr)); 
+0

申し訳ありませんが、私は言及すべきでした、私はこれを使用することはできません。私はそれを繰り返し行う必要があります。それはなぜ私がそれをこのようにしようとしているのか、私は再帰を使うことができません。 – Stardust1992

0
for(int i=0; i < count(original_array); i++) 
{ 
    if(i == 0) // check for first entry 
    { 
     new_array[] = original_array[i]; 
     temp = original_array[i]; 
    } 
    if(temp != original_array[i]) // check thereafter 
    { 
     new_array[] = original_array[i]; 
     temp = original_array[i]; 
    } 
} 
+0

'new_array [] = original_array [i];'これはまったくコンパイルされません。 –

+0

Hiiの友人、その行で、私はちょうどそれを伝えたい、新しい配列に古い値を入れて....コードは特定の言語のために書かれていません...それは単なる論理です... –

+0

ありがとう、それあまりにも働いた:) – Stardust1992

関連する問題