假设我们要为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<bits/stdc++.h>
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<V; i++)
{
//Note : Rows may not be contiguous
adj[i] = new bool [V];
//Initialize all entries as false to indicate
//that there are no edges initially
memset (adj[i], false , V* sizeof ( bool ));
}
}
//Utility method to print adjacency matrix
void Graph::print()
{
for ( int u=0; u<V; u++)
{
for ( int v=0; v<V; v++)
cout <<adj[u][v] <<" " ;
cout <<endl;
}
}
//Driver method
int main()
{
//Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.print();
return 0;
}
输出:
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));
本文作者:德莱拉吉·古普塔(Dheeraj Gupta)。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。