Graph class
Here's a simple Graph data structure that builds upon the previous Vertex data structure. The graph maintains an inner dictionary of all the vertices in it and a count of the vertices. There are functions to create vertex and add edges between two vertices that internally call Vertex member functions
Header
#ifndef __graphs__graph__
#define __graphs__graph__
#include
#include
#include
Source
#include "graph.h"
void Graph::addVertex(char id){
std::shared_ptr pv = std::make_shared(id);
_vertDict.insert(std::map>::value_type(id, pv));
_numVertices++;
}
void Graph::addEdge(char id1, char id2, int weight){
std::map>::iterator it1 = _vertDict.find(id1);
std::map>::iterator it2 = _vertDict.find(id2);
if (it1 == _vertDict.end() || it2 == _vertDict.end()) {
return;
}else{
it1->second->addNeighbor(weight, it2->second);
}
}
std::shared_ptr Graph::getvertex(char id){
std::map>::iterator it = _vertDict.find(id);
if (it != _vertDict.end()) {
return it->second;
}else{
return nullptr;
}
}
std::vector Graph::getVertices(){
std::vector ids;
for (std::map>::iterator iter = _vertDict.begin(); iter != _vertDict.end(); ++iter){
ids.push_back(iter->first);
}
return ids;
}
int Graph::getWeight(char id1, char id2){
std::map>::iterator it1 = _vertDict.find(id1);
std::map>::iterator it2 = _vertDict.find(id2);
if (it1 != _vertDict.end() && it2 != _vertDict.end()) {
return it1->second->getWeight(*it2->second);
}else{
return -1;
}
}
Test
#include
#include "vertex.h"
#include "graph.h"
int main(int argc, const char * argv[]) {
Graph g;
g.addVertex('a');
g.addVertex('b');
g.addVertex('c');
g.addEdge('a', 'b', 9);
g.addEdge('a', 'c', 5);
for (auto i: g.getVertices())
std::cout << i <<'\n';
std::shared_ptr v1;
v1 = g.getvertex('a');
for (auto i: v1->getConnections())
std::cout << i.second << ':'<< i.first <<'\n';
std::cout<< g.getWeight('a', 'b')<