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

4159ff6922a05946a214e4fd8095f7c6.png

假设我们要为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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值