new bool** matrix vs new bool*matrix vs new bool matrix 不同类型的cpp初始化混淆?
new bool** matrix vs new bool*matrix vs new bool matrix different types of cpp initialization confusion?
所以,经过我自己的研究,我知道 bool** 矩阵将创建二维数组,bool* 矩阵将创建一维数组。现在,当使用邻接矩阵
实现图形时
private:
bool** adjMatrix;
int numVertices;
public:
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVertices];//<---here
for (int i = 0; i < numVertices; i++) {
adjMatrix[i] = new bool[numVertices];//<--here
for (int j = 0; j < numVertices; j++)
adjMatrix[i][j] = false;
}
}
现在,我评论了我感到困惑的部分,根据我的上述理解,这两行看起来与我相似。
new bool*[numVertices]
分配并构造长度为 numVertices
的 bool*
(指向 bool
的指针)数组。 new bool[numVertices]
分配并构造长度为 numVertices
.
的 bool
数组
您的代码正在做什么:
- 将
adjMatrix
声明为指向 bool
的指针
- 设置
adjMatrix
指向bool*
数组的第一个元素
- 将该数组的每个元素设置为指向
bool
数组的第一个元素
这给出了 adjMatrix
看起来像二维数组的效果,因为您可以编写 adjMatrix[i][j]
并访问 bool
元素之一。但是,由于某些原因,此设置并不理想。
- 需要两次指针解引用才能到达一个数组元素,而不是一次
- 您必须执行
numVertices+1
动态分配
- 不保证对
new bool[numVertices]
的调用会在内存中将所有 bool
彼此相邻放置
最好让 adjMatrix
只是一个 bool*
,并立即分配所有布尔值:
adjMatrix = new bool[numVertices * numVertices];
这将为您节省 numVertices
动态分配并将所有 bool 放在一个连续的内存块中(更适合缓存)。然后您可以访问数组元素,例如
*(adjMatrix + i*numVertices + j)
而不是
adjMatrix[i][j]
所以,经过我自己的研究,我知道 bool** 矩阵将创建二维数组,bool* 矩阵将创建一维数组。现在,当使用邻接矩阵
实现图形时 private:
bool** adjMatrix;
int numVertices;
public:
Graph(int numVertices) {
this->numVertices = numVertices;
adjMatrix = new bool*[numVertices];//<---here
for (int i = 0; i < numVertices; i++) {
adjMatrix[i] = new bool[numVertices];//<--here
for (int j = 0; j < numVertices; j++)
adjMatrix[i][j] = false;
}
}
现在,我评论了我感到困惑的部分,根据我的上述理解,这两行看起来与我相似。
new bool*[numVertices]
分配并构造长度为 numVertices
的 bool*
(指向 bool
的指针)数组。 new bool[numVertices]
分配并构造长度为 numVertices
.
bool
数组
您的代码正在做什么:
- 将
adjMatrix
声明为指向bool
的指针
- 设置
adjMatrix
指向bool*
数组的第一个元素
- 将该数组的每个元素设置为指向
bool
数组的第一个元素
这给出了 adjMatrix
看起来像二维数组的效果,因为您可以编写 adjMatrix[i][j]
并访问 bool
元素之一。但是,由于某些原因,此设置并不理想。
- 需要两次指针解引用才能到达一个数组元素,而不是一次
- 您必须执行
numVertices+1
动态分配 - 不保证对
new bool[numVertices]
的调用会在内存中将所有bool
彼此相邻放置
最好让 adjMatrix
只是一个 bool*
,并立即分配所有布尔值:
adjMatrix = new bool[numVertices * numVertices];
这将为您节省 numVertices
动态分配并将所有 bool 放在一个连续的内存块中(更适合缓存)。然后您可以访问数组元素,例如
*(adjMatrix + i*numVertices + j)
而不是
adjMatrix[i][j]