2016-11-24 63 views
-2

C++中的錯誤刪除指向矢量數組的指針。 見下面的代碼,我需要「新」的矢量數組與V(頂點數量)大小。 btw,我有理由在這裏使用數組和「新」。請不要使用「新」/「刪除」操作來解決問題。C++刪除指向數組的指針<int>

class Graph 
{ 
    int V; // No. of vertices 
    vector<int> *adj; // An array of adjacency lists 
public: 
    Graph(int V); 
    ~Graph(); 
... 
}; 

// implementation 
Graph::Graph(int V) 
{ 
    this->V = V; 
    adj = new vector<int>[V]; 
} 

Graph::~Graph() 
{ 
    int v; 
    for (v = 0; v < V; v++) { 
     adj[v].clear(); 
    } 
    delete adj; 
} 


int main() 
{ 
    int V=100; 
    Graph g(V); 
    return 0; 
} 
+4

你應該使用'刪除[]'。而且,錯誤是什麼? – songyuanyao

+0

爲什麼你使用'vector *'? –

回答

3

您正在使用錯誤的delete。您需要使用陣列刪除(你也不需要明確clear()向量):

Graph::~Graph() 
{ 
    delete [] adj; 
} 

其實,你應該使用另一個std::vector,或std::unique_ptr,而不是存儲原始指針。

您也違反了Rule of Three,因爲不提供複製構造函數或複製賦值運算符。如果你要做到以下幾點,你將有嚴重的問題:

Graph f = g; 

存儲指針爲std::unique_ptr<std::vector<int>[]>將使上述非法的(除非你爲它的拷貝構造函數)。存儲std::vector<std::vector<int>>會使其默認行爲正確。

但既然你做手工,你將需要刪除的拷貝構造函數和拷貝賦值運算符,或提供自己:

Graph::Graph(const Graph & other) 
{ 
    V = other.V; 
    adj = new vector<int>[V]; 
    std::copy(other.adj, other.adj + V, adj); 
} 

Graph& Graph::operator=(const Graph & other) 
{ 
    if(this != &other) 
    { 
     Graph tmp(other); 
     std::swap(V, tmp.V); 
     std::swap(adj, other.adj); 
    } 
    return *this; 
} 
+0

我試過「delete [] adj;」它的工作原理。謝謝指出其他兩個問題。但std:; copy&std :: swap無法在adj上工作,我猜adj是指向數組的指針,而不是矢量。我會嘗試使用矢量>代替。 –