天天看點

c++動态數組是如何建立和使用的_如何在C++中的類内建立動态2D數組?

c++動态數組是如何建立和使用的_如何在C++中的類内建立動态2D數組?

假設我們要為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));
           

繼續閱讀