简体   繁体   中英

Am I accessing this vector variable correctly?

I'm trying to find where my code is seg faulting and I think it may have something to do with how I access a variable in the function below:

/****************************************************************
 * 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 is a private variable of the class Board:

private:
/****************************************************************
 * Variables.
**/
  vector< vector<int> > theBoard;

Do I need to separately declare and initiate the rowVector variable? If so, how would I do that?

You should check sizes or use .at to access variables that you are not sure of, ie:

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

or use try catch with .at

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

just an example/

You don't need to use this pointer inside a class member function to reference a class member variable, so

int Board::getSquare( int row, int col)
{
  vector<int> rowVector = this->theBoard[ row];

is equivalent to

int Board::getSquare(int row, int col)
{
  vector<int> rowVector = theBoard[ row];

Apart from this you are correct. Now, std::vector::operator[] returns a reference to the element ( because otherwise statements like std::vector v(1); v[0]=7; wouldn't compile - it is illegal to modify the return value of a function that returns a built-in type, and even if it were OK you would change a copy not original object), so you can simply write

int Board::getSquare( int row, int col)
{
    return theBoard[row][col];
}

if you are sure that you won't access out of bound elements. If you cannot guarantee such invariant add check for this, for example

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];
}

or use std::vector::at instead of operator[] .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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