I am trying to sort graph edges but am unable to do so. Given below is my implementation of a priority queue to achieve the same.
class CompareDistance
{
public:
bool operator()(pair<int,int> n1,pair<int,int> n2)
{
if(g[n1.first][n2.second] < g[n2.first][n2.second])
return true;
else
return false;
}
};
int g[3][3] = {{4,1,3},{3,3,3},{3,3,3}};//graph edges
int main()
{
priority_queue<pair<int,int>,vector<pair<int,int> >,CompareDistance> pq;
for(int i = 0 ; i < 3 ; i++)
for(int j = 0 ; j < 3 ; j++)
pq.push(pair<int,int>(i,j));
cout<<"\t"<<g[pq.top().first][pq.top().second];//does not give the correct result
pq.pop();
getch();
}
OK so if I understood you correctly you have a directed graph (like in example complete graph of three nodes). With each of the arc there is associated value -- weight and what you need is to sort the collection of arcs by this value. First of all you should probably create the collection of arcs. I don't think the priority_queue is the best of your option. I would use the vector here because of the simplicity:
std::vector<std::pair<int, std::pair<int, int>>> arcs;
Where the first pair would contain the arc weight and the directed pair of the nodes between which the arc exists. Next after you add all of the nodes you simply sort the collection specifing the custom function to compare. If you use c++11 it could look as follows:
std::sort(arcs.begin(), arcs.end(),
[] (const std::pair<int, std::pair<int, int>>& a,
const std::pair<int, std::pair<int, int>>& b) {
return a.first < b.first;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With