在C++中,将整数数组向量转换为二维数组可以通过以下步骤实现:
#include <vector>
#include <iostream>
std::vector<int> intVector = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int rows = 3;
int cols = 3;
std::vector<std::vector<int>> intArray(rows, std::vector<int>(cols));
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
intArray[i][j] = intVector[index];
index++;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << intArray[i][j] << " ";
}
std::cout << std::endl;
}
完整的代码示例如下:
#include <vector>
#include <iostream>
int main() {
std::vector<int> intVector = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int rows = 3;
int cols = 3;
std::vector<std::vector<int>> intArray(rows, std::vector<int>(cols));
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
intArray[i][j] = intVector[index];
index++;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << intArray[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
这段代码将整数数组向量 {1, 2, 3, 4, 5, 6, 7, 8, 9}
转换为一个3行3列的二维数组,并打印输出结果。
腾讯云相关产品和产品介绍链接地址:
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云