我正在尝试找到我的代码是段错误的地方,我认为它可能与我在下面的函数中访问变量的方式有关:
/****************************************************************
* 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:
/****************************************************************
* Variables.
**/
vector< vector<int> > theBoard;
我是否需要单独声明并启动rowVector变量?如果是这样,我该怎么做?
答案 0 :(得分:1)
您应该检查尺寸或使用.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
}
只是一个例子/
答案 1 :(得分:1)
您不需要在类成员函数中使用this
指针来引用类成员变量,所以
int Board::getSquare( int row, int col)
{
vector<int> rowVector = this->theBoard[ row];
相当于
int Board::getSquare(int row, int col)
{
vector<int> rowVector = theBoard[ row];
除此之外,你是对的。现在,std::vector::operator[]
返回对元素的引用(因为否则语句如std :: vector v(1); v [0] = 7;不会编译 - 修改函数的返回值是非法的返回一个内置类型,即使它是OK你也会改变副本而不是原始对象),所以你可以简单地写
int Board::getSquare( int row, int col)
{
return theBoard[row][col];
}
如果您确定不会访问超出范围的元素。如果你不能保证这样的不变量添加检查,例如
int Board::getSquare( int row, int col)
{
if ( !( row < theBoard.size())
throw std::out_of_range( "invalid row");
if ( !( col < theBoard[ row].size())
throw std::out_of_range( "invalid col");
return theBoard[ row][ col];
}
或使用std::vector::at
代替operator[]
。