Skip to content

Instantly share code, notes, and snippets.

@vineethak
Last active April 28, 2017 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vineethak/1d5e611303d480c48b7046cde04a2a05 to your computer and use it in GitHub Desktop.
Save vineethak/1d5e611303d480c48b7046cde04a2a05 to your computer and use it in GitHub Desktop.
simple generic graph class. which can be included as .h file in other graph related functions and can be used for any application related to graphs.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
template <class T>
struct s_vertex{
T num;
string name;
map<T, double> adjlist;
s_vertex(T v){
this->num = v;
};
s_vertex(T v, string name){
this->num = v;
this->name = name;
};
};
template <class T>
class Graph{
private:
int numVertices;
vector<s_vertex<T>> vertices;
vector<s_vertex<T>> vertexIterator;
public:
Graph(int V = 0){
this->numVertices = V;
}
void addVertex(T v){
s_vertex<T>* newVertex = new s_vertex<T> (v);
this->vertices.push_back(newVertex);
this->numVertices++;
return newVertex;
}
bool findVertex(T v){
for (this->vertexIterator = this->vertices.begin();
this->vertexIterator != this->vertices.end(); this->vertexIterator++){
if (this->vertexIterator->num == v){
return this->vertexIterator;
}
}
return false;
}
void addEdge(T src, T dst, double edgeWeight = 0){
s_vertex<T> srcVertex, dstVertex;
srcVertex = this->findVertex(src);
if (srcVertex == NULL)
srcVertex = this->addVertex(src);
dstVertex = this->findVertex(dst);
if (dstVertex == NULL)
dstVertex = this->addVertex(dst);
srcVertex.adjlist.push_back(make_pair(dst, edgeWeight));
dstVertex.adjlist.push_back(make_pair(src, edgeWeight));
}
};
int main(){
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment