📜  如何在C++中的类内创建动态2D数组?

📅  最后修改于: 2021-05-25 21:15:19             🧑  作者: Mango

假设我们要为Graph创建一个类。该类存储图的邻接矩阵表示。因此,我们的类结构如下所示。

class Graph 
{
  int V; 
  int adj[V][V];  // This line doesn't work
    
  /* Rest of the members */
};
  
int main()
{
}

输出 :

error: invalid use of non-static data
       member 'Graph::V'.

即使我们将V设为静态,也会出现错误“数组边界不是整数常量”

C++不允许在大小不恒定的类中创建堆栈分配的数组。因此,我们需要动态分配内存。下面是一个简单的程序,用于显示如何使用带有邻接矩阵表示形式的Graph类在C++类中动态分配2D数组。

// C++ program to show how to allocate dynamic 2D
// array in a class using a Graph example.
#include
using namespace std;
  
// A Class to represent directed graph
class Graph
{
    int V;    // No. of vertices
  
    // adj[u][v] would be true if there is an edge
    // from u to v, else false
    bool **adj;
  
public:
    Graph(int V);   // Constructor
  
    // function to add an edge to graph
    void addEdge(int u, int v)  { adj[u][v] = true; }
    void print();
};
  
Graph::Graph(int V)
{
    this->V = V;
  
    // Create a dynamic array of pointers
    adj = new bool* [V];
  
    // Create a row for every pointer
    for (int i=0; i

输出 :

0 1 1 0 
0 0 1 0 
1 0 0 1 
0 0 0 1 

关于调用memset()的注释:
memset()用于单独的行。我们不能将这些调用替换为一个调用,因为行被分配在不同的地址,并且进行如下所示的memset调用将是灾难性的。

// Wrong!! (Rows of matrix at different addresses)
       memset(adj, false, V*V*sizeof(bool));
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”