weighted graph

how to construct a weighted graph in c++ using stl’s

1> if you want to store just edges make

vector< pair< int, pair < int,int> > > edges.

pair of int(weight) and pair(a,b)(edge from atob).

or you can make pair of pair(a,b)(edge from atob) and int(weight).

2> if you want to store edges from perticular nodes.

vector< pair< int,int> > nodes[N];

for edges a to b with weight w you can insert as nodes[a].push_back(make _ pair(b,w))
indicating a has edge to b with weight w.

this 2 are just simple examples there are many ways to do so. :slight_smile:

If you do not know how vector and pair works use below links.

Link for PAIR || Link for Vector

EDIT: This approach will help you specially when you need to sort the edges according to weight.
you can use directly sort algorithm on vector as everything is mapped.

you can simply use:
N->no of nodes in the graph

vector<int> edges[N];//storing edges
vector<int> cost[N];//storing wieght

If you want to know the cost from a to b, in edges[a] search for b and using the index obtained extract the value from cost[a].

//