7

我正在尝试用 C++ 实现一个图形。我使用包含两个变量的结构来表示图中的节点 -
a) 一个包含有关节点的一些信息的整数。
b) 一个列表,其中包含与其相连的其他顶点的索引。
以下是代码。

// Graphs using adjacency list

#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;

// structure to represent a vertex(node) in a graph
typedef struct vertex{
    int info;
    list<int> adj;   // adjacency list of edges contains the indexes to vertex
} *vPtr;             

int main(){
    vPtr node = (vPtr)malloc(sizeof(struct vertex));
    node->info = 34;            // some arbitrary value
    (node->adj).push_back(2);   // trying to insert a value in the list
    return 0;
}

代码编译良好,但在推回列表中的元素时出现运行时错误。我的结构有什么问题吗?
我正在使用代码块和 GNU GCC、C++ 98 编译器来编译我的代码。

4

3 回答 3

10

malloc是一个 C 函数 - 它不应该与 C++ 对象一起使用,这在此处进行了很好的解释 (简短回答:在 C++ 中,当您不处理POD类型时,std::list在您的情况下,您必须调用对象的构造函数来获得准备使用的实际对象,malloc()但不这样做)。

你应该new改用. 虽然malloc只分配一块 size 的内存vertexnew但这样做并std::list通过调用它的构造函数来初始化(有趣的是,当你调用时delete(),你也在调用你的对象的析构函数)。

这是一段适用于您的案例的代码,尽管我建议您开始在 C++ 项目中使用更多 C++ 功能:

#include <iostream>
#include <list>
#include <cstdlib>
#include <new>

using namespace std;

// structure to represent a vertex(node) in a graph
typedef struct vertex{
    int info;
    list<int> adj;   // adjacency list of edges contains the indexes to vertex
} *vPtr;             

int main(){
    cout << "allocating memory for our vertex struct... \n";
    vPtr node = new vertex();
    node->info = 34;            // some arbitrary value
    (node->adj).push_back(2);   // trying to insert a value in the list
    cout << "cleaning allocated memory... \n";
    delete(node);

    return 0;
}
于 2013-07-29T17:33:21.073 回答
4

几件事。

  1. 因为您使用的是mallocnoconstructor被调用,因此非原始成员adj永远不会被构造并且为 NULL。
  2. 您正在泄漏内存,因为您从未释放/删除任何动态分配的内存。

  3. 如果您使用的是 C++,为什么要使用malloc而不是newand delete

  4. 您不必在sizeoffor C++ 中说 struct vertex。

要修复它,您可以执行以下操作:

vPtr node = new struct vertex(); // also change to delete instead of free

或者

// use current malloc line, change adj to be a pointer to a list and new it
// but this will cause additional problems for you since you really need to use a constructor for STL::list
node->adj = new list<int>;

你真的不应该在这里使用底线malloc

于 2013-07-29T17:29:27.883 回答
2

这是 UpAndAdam 的完整答案。

// Graphs using adjacency list
//
#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;

// structure to represent a vertex(node) in a graph
typedef struct vertex{
    int info;
    list<int> *adj;   // adjacency list of edges contains the indexes to vertex
} *vPtr;             

int main(){
    vPtr node = (vPtr)malloc(sizeof(struct vertex));
    node->adj = new list<int>;
    node->info = 34;            // some arbitrary value
    (node->adj)->push_back(2);  // trying to insert a value in the list
    return 0;
}
于 2013-07-29T18:08:18.057 回答