2015-11-24 122 views
0

這是使用遞歸解決Boggle棋盤遊戲的代碼。找到字典中的所有單詞後,當我檢查向量的大小時,我已經添加了單詞,找到了正確的單詞數量,但之後當我訪問函數外部的矢量時,我得到矢量的大小爲零。我使用「&」發送了向量的地址,但它似乎即使在該函數之外,矢量也沒有被更新。矢量不更新外部函數C++

這裏是我的函數wordCheck的代碼,我發送一個拼圖的副本,一行和一列以及一個名爲finalWord的空字符串。正如你所看到的,隨着單詞的添加,我會跟蹤矢量的大小,但是一旦函數經歷了可以用第一個字母形成的所有可能的單詞,即在r,c處的字母,矢量大小是正確的但是一旦我嘗試像在computerPlay()中一樣訪問它之外的循環,大小就會回到0,因此最後不會打印任何內容。在這個例子中,我只是測試第一個位置(0,0)。我也複製了computerPlay()的代碼。

void Boggle::computerPlay(){ 
//copy of boggle board 
    char boggleCopy[SET_ROWS][SET_COLUMNS]; 
    vector<string> computerWords; 
    for (int i = 0; i < SET_ROWS; i++) { 
     for (int j = 0; j < SET_COLUMNS; j++) { 
     boggleCopy[i][j] = theBoard[i][j]; 
     } 
    } 

string finalWord; 
wordCheck(boggleCopy, 0, 0, finalWord, computerWords); 


// here the vector size printed is Zero when in fact it should be 7 like it is inside the loop 
cout << "Vector size is " << computerWords.size() << endl; 
for (vector<string>::iterator i = computerWords.begin(); i != computerWords.end(); i++){ 
    cout << *i << endl; 
} 

} 



void Boggle::wordCheck(char puzzle[SET_ROWS][SET_COLUMNS], int r, int c, string finalWord, vector<string>& v){ 

char letter = puzzle[r][c]; 
finalWord = finalWord + letter; 
puzzle[r][c] = ' '; 
if (finalWord.length() > 2){ 
    if(dictionary.binarySearch(finalWord)){ 
     v.push_back(finalWord); 
     cout << v.size() << " is the size" << endl; 
    } 
} 
for(int dr = -1 ; dr <= 1 ; dr++){ 
    for(int dc = -1 ; dc <= 1 ; dc++){ 
     if (dr != 0 || dc != 0){ 
      if(finalWord.length() <= maxLength){ 
       if (!outOfBounds(r + dr, c + dc) && !(puzzle [r + dr][c + dc] == ' ')){ 
        if (finalWord.length() == 3){ 
         if(!(dictionary.isPrefix(finalWord))){ 
          break; 
         } 
        } 
        wordCheck(puzzle, r + dr, c + dc, finalWord, computerWords); 
       } 
      } 
     } 

    } 
} 
puzzle[r][c] = finalWord.at(finalWord.length() - 1); 
int size = v.size(); 
cout << "Last vector size is " << size << endl; 

// here my code prints out 7 as the size of the vector, which is the correct size that the vector should be. 
cout << "Last vector size is " << computerWords.size() << endl; 
} 
+0

你有computerWords作爲這個類的屬性? – ibrohimislam

回答

3

vector<string> computerWords;是一個局部變量來的computerPlay功能。當該函數退出時,它不再存在,並且其名稱在函數外部不可見。

如果您的代碼在wordCheck編譯,這意味着您的代碼中的其他位置有不同的向量(也稱爲computerWords)。

也許你的意思是不是有這等載體,併爲wordCheck功能使用參數v而非computerWords