使用一維陣列模擬C++中的二維陣列
在本問題中,我們將瞭解如何將二維陣列轉換為一維陣列。我們將學習如何將二維陣列的元素儲存到一維陣列中。
這裡,一維陣列的大小與二維陣列中元素的總數相同,即n*m。
在程式設計中,有兩種方法可以將二維陣列儲存到一維陣列中。它們是:
- 行優先
- 列優先
行優先:在行優先中,一行中的所有元素都一起儲存,然後移動到下一行。
如果大小為nXm的二維陣列的元素索引為(i, j),則其在一維陣列中的索引為
(j) + (i)*m
列優先:在列優先中,一列中的所有元素都一起儲存,然後遍歷下一列。
如果大小為nXm的二維陣列的元素索引為(i, j),則其在一維陣列中的索引為
(i) + (j)*n
讓我們看一個例子來理解這個問題:
輸入:n = 3, m = 5, (i,j) = (0, 2)
輸出:行優先 =
列優先 =
解釋:
行優先 = 2 + 0*3 = 2
列優先 = 0 + 2*5 = 10
演示二維陣列到一維陣列轉換的程式:
示例
#include<iostream>
using namespace std;
int main() {
int n = 3;
int m = 5;
int grid[n][m] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12},
{13, 14, 15}};
int i = 0;
int j = 2;
int rowMajorIndex = i*n + j;
cout<<"Index of element at index (0, 2) in 1-D array using row-major is "<<rowMajorIndex<<endl;
int colMajorIndex = i + j*m;
cout<<"Index of element at index (0, 2) in 1-D array using column-major is "<<colMajorIndex<<endl;
return 0;
}輸出:
Index of element at index (0, 2) in 1-D array using row-major is 2 Index of element at index (0, 2) in 1-D array using column-major is 10
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP