在动态分配的二维矩阵中插入新列

Inserting a new column in a dynamically allocated 2D Matrix

本文关键字:插入 新列 二维 动态分配      更新时间:2023-10-16

我想在二维动态分配的矩阵中添加一个新列。我已经设法制作了一种算法来添加新行,但是我不知道如何为列执行此操作。

我找到了用 C 写的东西,但我不知道如何用C++"翻译"它,如果你们中的任何人可以帮助或解释我该怎么做,我将不胜感激。

void AddColumn(int **matrix, int nrR,int &nrc,int *v,int position)
{
/* mat = (int**)realloc(mat, (nrc + 1) * sizeof(int*));
nrc++; What I found written in C*/
// nrc= number of columns
//mat=matrix
mat[nrc-1]=new int[nrc];// What I think it will be good
nrc++;
for(int index1=0;index1<nrR;index1++
{
for(int index2=nrc-1;index2>position;index2--)
{
matrix[index1][index2]=matrix[index1][index2-1];
}
}
for(int index3=position;index3<nrr;index3++) // REPLACE THE ELEMENTS WITH
{ //THE NEW COLUMN
matrix[index3][position]=v[index3];
}
}
}

另外,这是出于学习目的,这就是为什么我没有使用std::vector.

首先,格式良好的 C 可以很好地编译成C++,所以如果你的 C 代码不是特别脏,你可以按原样使用它。

但是让我们看看我会怎么做...

class TwoDArray {
private:
int ** data;
int width;
int height;
public:
TwoDArray(): data(nullptr), width(0), height(0) { }
~TwoDArray() { if (data != nullptr) {
...
}}
//
// use 0 for front of matrix.
//
void addColumn(int beforeLocation) {
int newWidth = width + 1;
for (int row = 0; row < height; ++row) {
int * oldRow = data[row];
int * newRow = new int[newWidth];
// Copy everything before the insert location
for (int col = 0; col < beforeLocation; ++col) {
newRow[col] = oldRow[col];
}
newRow[beforeLocation] = 0;
// Copy from the insert location forward
for (int col = beforeLocation; col < width; ++col) {
newRow[col + 1] = oldRow[col];
}
// Point data to use the new array of data and
// release the memory from the old one.
data[row] = newRow;
delete [] oldRow;
}
}
};

我还没有尝试编译这个。但是现在你会有一个知道整数的二维矩阵是什么的类。您将需要更多方法来访问,释放数据等。

所以......像这样。

一个简单的示例函数:

void AddColumn(int ** matrix, int numRows, int numCols)
{
/*
matrix[row][column]
example: rows = 4 cols = 5
---------------------------------
|   12  51  16  90  3   matrix[0][0-4]
|   34  1   4   0   7   matrix[1][0-4]
|   0   0   0   0   22  matrix[2][0-4]
|   0   0   0   0   88  matrix[3][0-4]
adding a column requires: reallocating every row array,
copying the values over, and deleting the old arrays
*/
int i = 0, j = 0; //index values
int *temp; // will hold a temporary copy of the old int array
for (;i < numRows; i++)
{
// reallocating
temp = matrix[i];
matrix[i] = new int[numCols + 1];
//copying old values
for (j = 0;j < numCols;j++)
matrix[i][j] = temp[j];
// ensuring the new values are initialized
// to a default value
matrix[i][numCols] = 0;
//deleting the old array
delete[] temp;
}//end for
/*
matrix should now be:
---------------------------------
|   12  51  16  90  3   0   matrix[0][0-5]
|   34  1   4   0   7   0   matrix[1][0-5]
|   0   0   0   0   22  0   matrix[2][0-5]
|   0   0   0   0   88  0   matrix[3][0-5]
*/
}//endfunc