我试图找到我的代码在哪里出现段错误,我认为这可能与我在下面的函数中访问变量的方式有关:
/****************************************************************
* Function for getting the value of a square.
**/
int Board::getSquare(int row, int col)
{
vector<int> rowVector = this->theBoard[row];
//gets desired row from theBoard
return rowVector[col];
//returns desired column of the row from theBoard
} // int Board::getSquare(int row, int col)
theBoard 是 Board 类的私有(private)变量:
private:
/****************************************************************
* Variables.
**/
vector< vector<int> > theBoard;
是否需要单独声明和初始化rowVector变量?如果是这样,我该怎么做?
最佳答案
您应该检查大小或使用 .at
来访问您不确定的变量,即:
if (this->theBoard.size() > row)
if (this->theBoard[row].size() > col)
return this->theBoard[row][col];
或者使用 try catch
和 .at
try {
return this->theBoard.at(row).at(col);
catch (...)
{
std::cerr << "wrong row col size" << std::endl
}
只是一个例子/
关于c++ - 我是否正确访问了这个 vector 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986944/