java
#include <iostream>
#include <vector>
class Array {
private:
std::vector<std::vector<int>> matrix;
int size;
public:
// 构造函数
Array(int n) : size(n) {
matrix.resize(n, std::vector<int>(n, 0));
}
// 设置矩阵元素
void setElement(int row, int col, int value) {
if (row >= 0 && row < size && col >= 0 && col < size) {
matrix[row][col] = value;
}
else {
std::cerr << "Error: Index out of bounds!" << std::endl;
}
}
// 获取矩阵元素
int getElement(int row, int col) const {
if (row >= 0 && row < size && col >= 0 && col < size) {
return matrix[row][col];
}
else {
std::cerr << "Error: Index out of bounds!" << std::endl;
return -1; // 返回-1表示错误
}
}
// 打印矩阵
void printMatrix() const {
for (const auto& row : matrix) {
for (int val : row) {
std::cout << val << " ";
}
std::cout << std::endl;
}
}
// 顺时针旋转90度
void rotate90Clockwise() {
std::vector<std::vector<int>> rotatedMatrix(size, std::vector<int>(size, 0));
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
rotatedMatrix[j][size - 1 - i] = matrix[i][j];
}
}
matrix = rotatedMatrix;
}
};
int main() {
int n;
std::cout << "Enter the size of the square matrix: ";
std::cin >> n;
Array arr(n);
std::cout << "Enter the elements of the matrix row by row:" << std::endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int value;
std::cin >> value;
arr.setElement(i, j, value);
}
}
std::cout << "Original matrix:" << std::endl;
arr.printMatrix();
arr.rotate90Clockwise();
std::cout << "Matrix after 90 degree clockwise rotation:" << std::endl;
arr.printMatrix();
return 0;
}
标签:std,int,实践,202411,&&,row,col,size
From: https://www.cnblogs.com/ejjw/p/18510644