I want to implement a directed graph which has 3 main kind of edges:
- self referencing edges
- non directional edges between two nodes
- directional edges between two nodes
Also I want to be able to do global operations on the graph, like e.g. counting or removing all edges fulfilling certain criteria.
The easiest program structure I came up with is:
#include <unordered_set>
using namespace std;
struct Edge;
struct Node
{
Node(std::string name):name(name){}
string name;
std::unordered_set<Edge*> edges;
};
struct Edge
{
Edge(Node * node1): node1(node1){}
double weight;
Node * node1;
};
struct EdgeBetweenTwoNodes: public Edge
{
EdgeBetweenTwoNodes(Node * node1, Node * node2 ): Edge(node1), node2(node2){}
Node * node2;
};
struct DirectionalEdge: public EdgeBetweenTwoNodes
{
DirectionalEdge(Node * node1, Node * node2, bool direction ): EdgeBetweenTwoNodes(node1,node2), direction(direction){}
bool direction;
};
struct EdgesContainer
{
std::unordered_set<Edge*> all_edges;
void register_new_edge(Edge * edge)
{
all_edges.insert(edge);
}
//do all kind of manipulations on all edges of a cetain type...
};
struct EdgeFactory
{
EdgeFactory(){}
void create_edge(Node* node1,EdgesContainer & edge_container)
{
Edge * edge = new Edge(node1);
node1->edges.insert(edge);
edge_container.register_new_edge(edge);
}
void create_edge(Node* node1, Node* node2, EdgesContainer & edge_container)
{
EdgeBetweenTwoNodes * edge = new EdgeBetweenTwoNodes(node1,node2);
node1->edges.insert(edge);
node2->edges.insert(edge);
edge_container.register_new_edge(edge);
}
void create_edge(Node* node1, Node* node2, bool direction, EdgesContainer & edge_container)
{
DirectionalEdge * edge = new DirectionalEdge(node1,node2,direction);
node1->edges.insert(edge);
node2->edges.insert(edge);
edge_container.register_new_edge(edge);
}
};
int main()
{
Node * A = new Node("A");
Node * B= new Node("B");
Node * C= new Node("C");
EdgesContainer edges;
EdgeFactory edge_factory;
edge_factory.create_edge(A,edges);
edge_factory.create_edge(A,B,edges);
edge_factory.create_edge(A,C,1,edges);
return 0;
}
What do you think about it? Is this the correct use of a so called "Factory?"
