簡體   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