向量未在函数C++外部更新

Vector not updating outside function C++

本文关键字:外部 更新 C++ 函数 向量      更新时间:2023-10-16

这是使用递归解决Boggle棋盘游戏的代码。在我找到字典中的所有单词后,当我检查添加单词的向量的大小时,会找到正确的单词数量,但之后当我访问函数外的向量时,我得到向量的大小为零。我已经用"&"发送了矢量的地址,但即使这样,矢量似乎也没有在函数之外更新。

这是我的函数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;
}

vector<string> computerWords;computerPlay函数的局部变量。当该函数退出时,它不再存在,并且它的名称在函数外部不可见。

如果您的代码在wordCheck中编译,则意味着您的代码中的其他地方有一个不同的向量(也称为computerWords)。

也许您的意思是没有这个其他向量,并且wordCheck函数使用参数v而不是computerWords