Simple Graph implementation for Beginners in C++
Graph are one of the most interesting topic to be discussed, but many who begin get confused as to how to implement it. There are many way to implement a graph here is one of the simplest implementation. Where the no. of vertex and the info about the edge is taken as an input.
#include<iostream> #include<string> #include<vector> using namespace std; struct Edge { int destination; int weight; }; void printGraph(vector< vector<Edge> > v){ for(int i=0;i<v.size(); i++){ // same thing can also be done using iterator; cout<<i<<": "; for(int j=0;j<v[i].size();j++) cout<<v[i][j].destination<<" "; } } Edge getEdge(int dest, int weight=0){ Edge e; e.destination = dest; e.weight = weight; return e; } int main(){ vector< vector<Edge> > g; // destination of each vertex here max is choosen as 20; int dest[20]; int n;//number of vertex; cout<<"Enter the no of vertex\n"; cin>>n; for(int i=0;i<n;i++){ cin.sync(); cout<<"Enter no of edges"; int ne; cin>>ne; cout<<"Enter all the destination"; for(int j=0;j<ne;j++) cin>>dest[j]; // enter all destination in one line here 1 2 3 4 etc. vector<Edge> temp; for(int j=0;j<ne;j++){ // weight is kept at zero, can be passed here. Edge e = getEdge(dest[j]); temp.push_back(e); } g.push_back(temp); temp.clear(); } printGraph(g); return 0; }The graph in the above is directed graph so if an undirected graph is made one should keep in mind about adding the symmetric edge too. Here The weight is given a default value of zero if one wants to assign weight to different edge , with the destination also pass the weight of the edge. This is an implementation using vector, map or list can also be used according too the need.
0 comments