一维数组赋值给二维数组

编程入门 行业动态 更新时间:2024-10-27 08:31:57

一维<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组赋值给二维数组"/>

一维数组赋值给二维数组

一, 逐个点的赋值(单个循环)

一维数组又[56],是一个30个元素的数组,将他赋值给一个[56]五行六列的二维矩阵中,一位数组和二维矩阵的
坐标转换:[i/列数][i%列数]

	// 赋值给二维矩阵// i从0~一维数组个个数,仅一个循环for (int i = 0; i < rows * cols; i++){matrix[i / cols][i % cols] = one_matrix[i];  坐标转换[i/列数][i%列数]}

示例:

int main()
{int rows = 5; // 行数int cols = 6; // 列数int* one_matrix = new int[rows * cols];  // 申请一维数组空间for (int i = 0; i < rows * cols; i++){one_matrix[i] = i;}std::vector<std::vector<int>> matrix;matrix.resize(rows,std::vector<int>(cols)); // 申请二维数组空间// 赋值给二维矩阵for (int i = 0; i < rows * cols; i++){matrix[i / cols][i % cols] = one_matrix[i];  // 坐标转换[i/列数][i%列数]}// 打印查看for (int i = 0; i < rows ; i++){for (int j = 0; j < cols ; j++){std::cout << matrix[i][j] << " ";}std::cout << std::endl;}delete[] one_matrix;return 0;
}打印查看
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
24 25 26 27 28 29

二,使用memcpy方式赋值

	// 使用memcpy进行赋值for (int i = 0; i < rows; i++){memcpy(matrix[i].data(), &one_matrix[i * cols], cols * sizeof(i));// 或者memcpy(&matrix[i][0], &one_matrix[i * cols], cols * sizeof(i));}
int main()
{int rows = 5;int cols = 6;int* one_matrix = new int[rows * cols];for (int i = 0; i < rows * cols; i++){one_matrix[i] = i;}std::vector<std::vector<int>> matrix;matrix.resize(rows,std::vector<int>(cols));// 使用memcpy进行赋值for (int i = 0; i < rows; i++){memcpy(matrix[i].data(), &one_matrix[i * cols], cols * sizeof(i));// 或者memcpy(&matrix[i][0], &one_matrix[i * cols], cols * sizeof(i));}//打印查看for (int i = 0; i < rows ; i++){for (int j = 0; j < cols ; j++){std::cout << matrix[i][j] << " ";}std::cout << std::endl;}delete[] one_matrix;return 0;
}

更多推荐

一维数组赋值给二维数组

本文发布于:2023-12-04 18:37:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1661859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   赋值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!