Last active
April 28, 2017 11:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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