包含另一个对象指针向量的对象



我知道我不能拥有连接向量,因为它包含一个在代码行中还不存在的对象。我无法切换订单,因为顶点还不存在。

struct Vertex {
    int key;
    int val;
    vector<Edge*> connections;
    Vertex(int k) {
        key = k;
    }
};

struct Edge {
    Vertex *start;
    Vertex *end;
    int weight;
    Edge(Vertex *s, Vertex *e, int w) {
        start = s;
        end = e;
        weight = w;
    }
};

所以我对此的解决方案是创建一个新对象并将连接放在那里。

struct Node {
    int key;
    int val;
    Node(int k) {
        key = k;
    }
};

struct Edge {
    Node *start;
    Node *end;
    int weight;
    Edge(Node *s, Node *e, int w) {
        start = s;
        end = e;
        weight = w;
    }
};
struct Vertex {
    Node node;
    vector<Edge*> connections;
};

有更好的选择,我只需要保留两个对象而不是三个对象?

您只需要转发declare Edge

struct Edge;
struct Vertex {
    int key;
    int val;
    vector<Edge*> connections;
    Vertex(int k) {
        key = k;
    }
};

最新更新