c++ - 我是否正确访问了这个 vector 变量?

标签 c++ vector segmentation-fault std declaration

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

/****************************************************************
 * 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/

相关文章:

c++ - 查找奇 vector 元素 C++

c - 从 64 位机器中的 C 函数访问返回地址时出现段错误

c++ - Itanium ABI 在多大程度上真正指定了填充和对齐?

c++ - 无法在 OpenCV 中获取直方图图像

c++ - 派生类中指向基类的指针 vector

java - 集合 : Array, Vector 和 ArrayList。区别和正确用法

c++ - 重载运算符中的段错误 =

c++ - 为什么会出现段错误?

c++ - 有没有感觉 c++ 有时会减少解决问题的时间并增加句法、语义的严谨性?

c++ - 二分查找的逻辑