#Graph help

8 messages · Page 1 of 1 (latest)

neat grove
#

Hello Someone yesterday tried helping me and this is actually his code, which I'm using to demonstrate the problem im encountering. Below is the header.h file and main file respectively. He claimed that this code would work but I cannot get a successfull result. I think the reason why is cause edge is reliant on vertex and vertex is reliant on edge which isnt allowed. Any way around this?

#pragma once
#include <vector>

class Edge {
public:
    Vertex* vertex1;
    Vertex* vertex2;

    Edge(Vertex* v1, Vertex* v2) : vertex1{ v1 }, vertex2(v2) {}
};

class Vertex {
    public:
        std::vector<Edge*> incidentEdges;

        void addEdge(Edge* edge) {
            incidentEdges.push_back(edge);
        }
};

class Graph {
public:
    std::vector<Vertex*> vertices;
    std::vector<Edge*> edges;
};
#include <iostream>
#include "Header.h"
int main()
{
    
    std::cout << "Hello World!\n";
}
blissful raftBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

limber vapor
# neat grove Hello Someone yesterday tried helping me and this is actually his code, which I'...

The problem is that for circular type-dependencies, you have to forward-declare the types, so that the first class knows there's a second one coming:

#pragma once
#include <vector>

class Vertex;
class Edge; // Just in case you want to change the ordering of Vertex and Edge

class Edge {
public:
    Vertex* vertex1;
    Vertex* vertex2;

    Edge(Vertex* v1, Vertex* v2) : vertex1{ v1 }, vertex2(v2) {}
};

class Vertex {
    public:
        std::vector<Edge*> incidentEdges;

        void addEdge(Edge* edge) {
            incidentEdges.push_back(edge);
        }
};

class Graph {
public:
    std::vector<Vertex*> vertices;
    std::vector<Edge*> edges;
};
int main() {}
mental notchBOT
#
Compiler Output
<source>:1:9: warning: #pragma once in main file
    1 | #pragma once
      |         ^~~~
neat grove
#

omg thats so simple

#

thank you!

#

!close