patterncppMinor
Graph implementation adjacency list 1.0
Viewed 0 times
implementationlistgraphadjacency
Problem
Please note the following:
```
void
Graph::insert_edge( Node n, Node new_edge )
{
if( n == nullptr || new_edge == nullptr )
{
return;
}
if( !is_node( n ) )
{
return;
}
for( auto& node : list )
{
if( n -> get_name() == node -> get_name() )
{
for( auto& current_edges : node -> neighbours )
{
if( current_edges -> get_name() == new_edge -> get_name() )
{
- All edges are directed
- Removal of edges/nodges is not implemented yet
- A user of the class
Graphcan never (hopefully) access aNodedirectly
- If one tries to add an edge to a node that does not exist,
insert_edge()will do nothing.
- A
Vertexcannot point to another vertex with several edges.
- While the base class
Graphworks perfectly, I would like to create more advance graphs that could be used for maximum flow algorithm, weighted graphed etc. by creating new classes and inherit functions fromGraph. But this seems impossible by the current implementation. It seems that the only way for a smooth solution for this right now is to add more data members toNode(int weightfor example). Any idea on what I can do for making this possible with inheriting fromGraphinstead?
class Node
{
public:
std::string get_name()const;
//protected:
Node() = default;
Node( const std::string & n )
: name(n)
{}
std::vector neighbours;
private:
std::string name;
};class Graph : public Node
{
public:
void insert_node( std::string);
void insert_edge( std::string, std::string);
void print_node( const std::string) const;
void print_graph() const;
protected:
void insert_edge( Node*, Node*);
Node* get_node( std::string ) const;
bool is_node( Node * );
private:
std::vector list;
};std::string
Node::get_name() const
{
return name;
}void
Graph::insert_node( std::string name)
{
for( auto& node : list )
{
if( name == node -> get_name() )
{
return;
}
}
Node *temp = new Node(name);
list.push_back ( temp );
}```
void
Graph::insert_edge( Node n, Node new_edge )
{
if( n == nullptr || new_edge == nullptr )
{
return;
}
if( !is_node( n ) )
{
return;
}
for( auto& node : list )
{
if( n -> get_name() == node -> get_name() )
{
for( auto& current_edges : node -> neighbours )
{
if( current_edges -> get_name() == new_edge -> get_name() )
{
Solution
I don't like that
As for you question of adding a data member weight in
std::vector neighbours; is a data member with public scope in Node. I would suggest doing it private and provide a getter for it, or provide a Node::push_back(), etc.As for you question of adding a data member weight in
Graph, I think that's not very nice, since - in my mind - weight is an attribute every node has, thus it should be a data member of Node.Context
StackExchange Code Review Q#75013, answer score: 2
Revisions (0)
No revisions yet.