Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++删除矢量数组INT>指针 < C++中的错误>删除指向向量数组的指针。 请参阅下面的代码,我需要使用Vvertex num size创建向量的新数组。 顺便说一句,我有理由在这里使用数组和new。请不要通过不使用新建/删除操作来解决此问题 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; }_C++_Pointers_Vector - Fatal编程技术网

C++删除矢量数组INT>指针 < C++中的错误>删除指向向量数组的指针。 请参阅下面的代码,我需要使用Vvertex num size创建向量的新数组。 顺便说一句,我有理由在这里使用数组和new。请不要通过不使用新建/删除操作来解决此问题 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; }

C++删除矢量数组INT>指针 < C++中的错误>删除指向向量数组的指针。 请参阅下面的代码,我需要使用Vvertex num size创建向量的新数组。 顺便说一句,我有理由在这里使用数组和new。请不要通过不使用新建/删除操作来解决此问题 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; },c++,pointers,vector,C++,Pointers,Vector,您使用了错误的删除。您需要使用数组删除,也不需要显式清除向量: Graph::~Graph() { delete [] adj; } 实际上,您应该使用另一个std::vector或std::unique_ptr,而不是存储原始指针 未提供复制构造函数或复制赋值运算符也违反了。如果您执行以下操作,您将遇到严重问题: Graph f = g; 将指针存储为std::unique\u ptr将使上述内容非法,除非为其创建了副本构造函数。默认情况下,存储std::vector将使其行为正

您使用了错误的删除。您需要使用数组删除,也不需要显式清除向量:

Graph::~Graph()
{
    delete [] adj; 
}
实际上,您应该使用另一个std::vector或std::unique_ptr,而不是存储原始指针

未提供复制构造函数或复制赋值运算符也违反了。如果您执行以下操作,您将遇到严重问题:

Graph f = g;
将指针存储为std::unique\u ptr将使上述内容非法,除非为其创建了副本构造函数。默认情况下,存储std::vector将使其行为正确

但由于您是手动执行此操作,因此您需要删除复制构造函数和复制赋值运算符,或者提供自己的:

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;
}

您应该使用delete[]。那么,错误是什么呢?你到底为什么要使用向量*?我试着删除[]adj;它是有效的。谢谢你指出另外两个问题。但是性病:;swap不能在adj上工作,我猜adj是指向数组的指针,而不是向量。我将尝试使用vector。