2017-02-01 3 views
0
ArrayBag foundBag; 
    int z; 
    z = getCurrentSize(); // tell you have many items exit in the bag 
    for (int i = 0; i < z; i++) 
    { 
     int cur = items[i]; //cur is use to hold each number in the vector and items is the first list of number. 
     bool found = false; // start as false so it doesnt trigger the true right away 
     for (int j = 0; j < foundBag.getCurrentSize(); j++) // this loop check the number currently inside cur agianst everything in the foundbag at the moment 
     { 
      if (foundBag.items[i] = cur) 

      { 
       found == true; // << it didnt detect that it have found the number. I think the problem is here 
      } 
     } 
     if (found == true) 
     { 
      // do nothing if found since number is already in the foundbag 
     } 
     else if (found != true) 
     { 
      foundBag.add(cur); // if number is not found in the foundBag add it to the found bag. 
     } 
    } 

私がしようとしているのは、既存のリストの値をこの場合はfoundBagと呼ばれる新しい空の値と比較することです。だから、基本的には最初の袋から値を得て、その袋が最初の袋に入っていないかどうかを調べる。見つからなければその数をfoundBagに加える。すでに番号が見つかった場合は何もせず、最初のバッグの次の要素に移動します。C++ 2つの異なるリストからの値を比較して、2 forループを使用して重複数を取り除く。

最初のバッグの番号が3 4 5 7 5 8であれば、3 4 5 7からすべてを追加し、次に2番目の5に到達したら何もしないで、foundBagに8を加えます。 最後のfoundBagには以下が含まれている必要があります:3 4 5 7 8

問題は、その番号が既にfoundBagにあることを正しく検出してすべてを追加するようです。 私はビジュアルスタジオのステップオーバー機能を使って各ステップを見ていましたが、なぜ同じ番号が見つかったときにブールがまだfalseになるのか理解できませんでした。このdoesntのメイクセンスは、より説明をお願いしてくださいので、もし英語でイムは非常に強力ではない

はあなた===が混ざっているように見えます

答えて

1

ありがとうございます。ところで

 if (foundBag.items[j] == cur) // Use == here for comparison 
     { 
      found = true; // Use = here for assignment 
     } 

、あなたがやっているすべては、コレクション内の要素を探している場合は、標準ライブラリからアルゴリズムを好む:

auto result = std::count(std::begin(foundBag.items), std::end(foundBag.items), cur); 
if (result == std::end(foundBag.items)) { 
    // Not found; Add it 
    foundBag.add(cur); 
} 
+1

あなたは、インデックスを変更する必要があるようにあなたはまた見ます「i」から「j」まで。 –

関連する問題