繁体   English   中英

我可以正确访问此向量变量吗?

[英]Am I accessing this vector variable correctly?

我试图找出我的代码在哪里出现段错误,我认为这可能与我在下面的函数中访问变量的方式有关:

/****************************************************************
 * 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变量? 如果是这样,我该怎么做?

您应该检查大小或使用.at来访问不确定的变量,即:

if (this->theBoard.size() > row)
    if (this->theBoard[row].size() > col)
        return this->theBoard[row][col];

或使用.at try catch

try {
   return this->theBoard.at(row).at(col);
catch (...)
{
   std::cerr << "wrong row col size" << std::endl
}

只是一个例子/

您不需要在类成员函数中使用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;这样的语句将无法编译-修改返回值是非法的返回内置类型的函数的值,即使可以,也可以更改副本而不是原始对象),因此您可以简单地编写

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[]

http://en.cppreference.com/w/cpp/container/vector

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM