lyph lyph - 10 days ago 5
C++ Question

Object containing vector of pointers of another object

I know I can't have the connection vector because it contains an object that doesn't exist yet at that line of code. I can't switch the order because Vertex doesn't exist yet.

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


So my solution to this is create a new object and placing connections in there.

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


Is there a better alternative where I only need to keep two objects instead of three?

Answer

You just need to forward-declare Edge:

struct Edge;

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