假设我们要为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设为静态,也会出现错误“array bound is not an integer constant”。
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));