简体   繁体   English

用于对图形边缘进行排序的C ++ Priority Queue实现

[英]C++ Priority Queue implementation to sort graph edges

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. 我不认为priority_queue是你最好的选择。 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: 如果你使用c ++ 11,它可能如下所示:

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; 
              });

Your code does not compile, but that is an easy fix. 您的代码无法编译,但这是一个简单的修复。 I assume g contains the edge weights. 我假设g包含边权重。 There is a bug in here: 这里有一个错误:

if(g[n1.first][n2.second] < g[n2.first][n2.second])

It should be 它应该是

if(g[n1.first][n1.second] < g[n2.first][n2.second])

Mind the name of the second index on the left. 记住左边第二个索引的名称。 Live On Coliru 住在Coliru

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM