在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;
}
通過這些錯誤處理和異常機制,你可以確保網格在使用過程中的健壯性和穩定性。