小红的矩阵构造c++
时间: 2024-06-14 16:04:30 浏览: 61
以下是一个用C++构造小红矩阵的示例代码:
```cpp
#include <iostream>
#include <vector>
std::vector<std::vector<int>> constructMatrix(int n) {
std::vector<std::vector<int>> matrix(n, std::vector<int>(n, 0));
int a = 1, b = 2;
for (int i = 0; i < n * n; i++) {
if ((i / n + i % n) % 2 == 0) {
matrix[i / n][i % n] = a;
a += 2;
} else {
matrix[i / n][i % n] = b;
b += 2;
}
}
return matrix;
}
int main() {
int n;
std::cin >> n;
std::vector<std::vector<int>> res = constructMatrix(n);
for (const auto& row : res) {
for (int x : row) {
std::cout << x << " ";
}
std::cout << std::endl;
}
return 0;
}
```
阅读全文