我正在实现我自己的一组用于表示图形的类。 我是C ++的新手,所以我在使用指针时遇到了一些麻烦。 你看,这是我原来的代码:
class Vertex { public: int label; Vertex adjacent_vertices[]; Vertex(int l) : label(l) { } Vertex(int l, Vertex adjacents[]) : label(l), adjacent_vertices(adjacents) { } };但后来我得到了一个不完整的类型错误。 根据我的研究,我显然需要使用adjacent_vertices的指针列表。 Vertex* adjacent_vertices[]; 但是第二个构造函数存在问题。 这些都不起作用:
adjacent_vertices(*adjacents) adjacent_vertices(adjacents*) adjacent_vertices(&adjacents)有没有更好的方法来实现这个? 我觉得这里有一些我非常明显的东西,作为Java / Python开发人员之前从未使用过指针。
I'm implementing my own set of classes for representing graphs. I'm new to C++, so I'm having some trouble with pointers. You see, this was my original code:
class Vertex { public: int label; Vertex adjacent_vertices[]; Vertex(int l) : label(l) { } Vertex(int l, Vertex adjacents[]) : label(l), adjacent_vertices(adjacents) { } };but then I get an incomplete type error. From my research, I apparently need to use a list of pointers for adjacent_vertices. Vertex* adjacent_vertices[]; But then there's a problem with the second constructor. None of these worked:
adjacent_vertices(*adjacents) adjacent_vertices(adjacents*) adjacent_vertices(&adjacents)Is there a better way to implement this? I feel like there's something very obvious I'm missing here, as a Java/Python dev who's never worked with pointers before.
最满意答案
一个简单的解决方案是使用矢量作为您的adjacent_vertices。
class Vertex { public: int label; vector<Vertex> adjacent_vertices; Vertex(int l) : label(l) { } Vertex(int l, vector<Vertex> adjacents) : label(l), adjacent_vertices(adjacents) { } };An easy solution would be to use vector for your adjacent_vertices.
class Vertex { public: int label; vector<Vertex> adjacent_vertices; Vertex(int l) : label(l) { } Vertex(int l, vector<Vertex> adjacents) : label(l), adjacent_vertices(adjacents) { } };更多推荐
发布评论