2017-05-16 22 views
1

プログラム内のループの設定方法に問題があります。ちょっとしたデバッグをした後、私は、最後の反復まで、tempがターゲットに一致する直前まで、ループがすべて実行されていることを理解しました。 EXC_BAD_ACCESS (code=1, address=0x0)がスローされ、プログラムが終了します。 (11)STLセットを反復できません

bool isadjacent(string& a, string& b) 
{ 
    int count = 0; 
    int n = a.length(); 

    for (int i = 0; i < n; i++) 
    { 
     if (a[i] != b[i]) count++; 
     if (count > 1) return false; 
    } 
    return count == 1 ? true : false; 
}  


int shortestChainLen(string& start, string& target, set<string> &D) 
{ 
    queue<QItem> Q; 
    QItem item = {start, 1}; 
    Q.push(item); 
    while (!Q.empty()) 
    { 
     QItem curr = Q.front(); 
     Q.pop(); 
     for (set<string>::iterator it = D.begin(); it != D.end(); it++) 
     { 
      string temp = *it; 
      if (isadjacent(curr.word, temp)) 
      { 
       item.word = temp; 
       item.len = curr.len + 1; 
       Q.push(item); 
       D.erase(temp); 
       if (temp == target) 
        return item.len; 
      } 
     } 
    } 
    return 0; 
} 

これはXCodeデバッガの検出結果ですが、これをどのように解釈するのかはわかりません。 enter image description here

答えて

3

問題 は、反復子が無効化され、それのいずれかの更なる使用は、あなたのイテレータが現在行それが起こる

D.erase(temp); 

上でポイントセットの要素を消去しているということです未定義の動作。

イテレータを取り、次の項目を参照するイテレータを返す erase方法を使用して
for (set<string>::iterator it = D.begin(); it != D.end();) { 
     if (isadjacent(curr.word, *it)) { 
      item.word = *it; 
      item.len = curr.len + 1; 
      Q.push(item); 
      it = D.erase(it); 
      if (item.word == target) 
       return item.len; 
     } else { 
      ++it; 
     } 
    } 

:あなたは代わりとして、あなたのコードを構築したいです。

+0

ありがとうございました。私はこれを何時間も働いており、私はそれを逃したとは思えません。 – Malcolm

関連する問題