C++ 中多维数组之间的快速转换(以1维2维数组的相互转换为例说明)

在图像处理中,大规格的数组之间的转换是家常便饭。

c++中多维数组在本质上就是一个地址问题,普通情况下,可以通过类似如下方法进行暴力转换

int arr[50];

int main()
{
	unsigned i, j;
	for (i = 0; i < 50; i++) {
		arr[i] = 2 * i;
	}

	int bruteArray[7][7];
	for (i = 0; i < 7; i++)
		for (j = 0; j < 7; j++)
			bruteArray[i][j] = arr[i * 7 + j];
	cout << "[0][0]=" << bruteArray[0][0] << endl;
	cout << "[1][0]=" << bruteArray[1][0] << endl;
	

    return 0;
}

不过这样的话,开销比较大,效率就成了一个问题,尤其是在处理大规模矩阵式多维数组时,所以一般采取直接进行地址转换的方式,不必逐个从内存拷贝,就能得到正确的转换。


#include <iostream>
#include <stdio.h>
using namespace std;

int arr[50];

int main()
{
	unsigned i, j;
	for (i = 0; i < 50; i++) {
		arr[i] = 2 * i;
	}

	//method1 -- convert 1d array to 2d
	cout << "------------------------------------------------------" << endl;
	int *pa[7];
	for (j = 0; j < 7; j++) {
		pa[j] = &arr[j*7];
		for (i = 0; i < 7; i++) {
			cout << pa[j][i] << endl;
		}
	}

	//method2 -- 
	cout << "------------------------------------------------------" << endl;
	int array1[] = { 1,2,3,4,5,6,7,8,9,10 };
	int array2[] = { 9,8,7,6,5,4,3,2,1,0 };
	int *arr2d[2];
	arr2d[0] = array1;
	arr2d[1] = array2;
	cout << "[0][0]=" << arr2d[0][0] << endl;
	cout << "[1][0]=" << arr2d[1][0] << endl;

	//method3 -- 
	cout << "------------------------------------------------------" << endl;
	int *arr2dv[] = { array1, array2 };
	cout << "[0][0]=" << arr2dv[0][0] << endl;
	cout << "[1][0]=" << arr2dv[1][0] << endl;

	
	//method test0 -- convert 2d array to 1d
	cout << "------------------------------------------------------" << endl;
	int test2d[2][10] = { { 1,2,3,4,5,6,7,8,9,10 },{ 9,8,7,6,5,4,3,2,1,0 } };
	int *test1 = test2d[0];
	int *test2 = test2d[1];
	cout << "[0][0]=" << test1[0] << endl;
	cout << "[1][0]=" << test2[1] << endl;

	return 0;
}

对于动态创建数组的情况,

int step = n;  // columns
int rows = m;
int tot = m*n; // assume m rows, n columns
double* data = new double[tot]; 
double ** matrix = new double* [m];
for (int i = 0; i < m; i++) {
    matrix[i] = &data[(int)(step * i)];
}

// do something here for matrix manipulation
// 这里干点什么。。。。例如,
matrix[i][j] = 1234;
//....

delete[] matrix;
delete[] data;

对于更高维数的数组,原理也是一样的。

下面演示一个三维数组的情况,该数组可以直接采用pmem[page][y][x]的形式快速访问。

const int COLOR_NUM = 10;
unsigned char* maskMem = (unsigned char*)malloc(totSize);
memset(maskMem, 0, totSize);
unsigned char *** pmem = new unsigned char** [COLOR_NUM];
int x = 0, y = 0, page = 0;
for (int clr = 0; clr < COLOR_NUM; clr++) {
	pmem[clr] = new unsigned char* [ht];   // similar layer border marker (-10 for ext, 10 for inner) matrix
	page = clr * mskSize;
	for (y = 0; y < ht; y++) {
		x = page + y * wd;
		pmem[clr][y] = &maskMem[x];
	}
}

另外,网上有人用memcpy的方式来实现内存的直接拷贝,这种方法并不能一直正确,因为多维数组取决于你创建的方式,内存未必是连续的。

posted @ 2019-06-27 14:34  SpaceVision  阅读(148)  评论(0编辑  收藏  举报