阅读量:81
在C++中,网格(Grid)通常是指一个二维数组,用于存储和操作二维空间中的数据
- 越界检查:在访问网格元素时,确保行和列索引在有效范围内。如果索引超出范围,可以抛出一个异常或返回一个错误码。
class Grid {
public:
// ...
int& at(int row, int col) {
if (row < 0 || row >= rows_ || col < 0 || col >= cols_) {
throw std::out_of_range("Index out of bounds");
}
return data_[row][col];
}
private:
int rows_;
int cols_;
std::vectorint>> data_;
};
- 初始化检查:在创建网格时,确保行数和列数大于0。如果不满足条件,可以抛出一个异常或返回一个错误码。
class Grid {
public:
Grid(int rows, int cols) {
if (rows <= 0 || cols <= 0) {
throw std::invalid_argument("Rows and columns must be greater than 0");
}
rows_ = rows;
cols_ = cols;
data_.resize(rows, std::vector<int>(cols));
}
// ...
};
- 内存分配检查:在分配内存时,确保分配成功。如果分配失败,可以抛出一个异常或返回一个错误码。
class Grid {
public:
// ...
void resize(int newRows, int newCols) {
if (newRows <= 0 || newCols <= 0) {
throw std::invalid_argument("Rows and columns must be greater than 0");
}
try {
data_.resize(newRows, std::vector<int>(newCols));
} catch (const std::bad_alloc& e) {
throw std::runtime_error("Memory allocation failed");
}
rows_ = newRows;
cols_ = newCols;
}
private:
// ...
};
- 使用异常处理:在调用可能抛出异常的函数时,使用try-catch语句来捕获和处理异常。
int main() {
try {
Grid grid(3, 3);
int value = grid.at(5, 5); // This will throw an exception
} catch (const std::exception& e) {
std::cerr << "Error: " << e class="hljs-built_in">what()<< std class="hljs-keyword">return 1;
}
return 0;
}
通过这些错误处理和异常机制,你可以确保网格在使用过程中的健壮性和稳定性。