在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::vector<std::vector<int>> data_;
};
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:
// ...
};
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.what()<< std::endl;
return 1;
}
return 0;
}
通过这些错误处理和异常机制,你可以确保网格在使用过程中的健壮性和稳定性。