[英]C++ Priority Queue implementation to sort graph edges
我試圖排序圖形邊緣但我無法這樣做。 下面給出的是我實現的優先級隊列實現相同。
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();
}
好的,如果我理解正確,你就會有一個有向圖(就像三個節點的示例完整圖一樣)。 每個弧都有相關的值 - 權重,你需要的是按這個值對弧的集合進行排序。 首先,您應該創建弧的集合。 我不認為priority_queue是你最好的選擇。 我會在這里使用向量因為簡單:
std::vector<std::pair<int, std::pair<int, int>>> arcs;
其中第一對將包含弧重和弧之間存在的有向節點對。 在添加所有節點之后,您只需對指定要比較的自定義函數的集合進行排序。 如果你使用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;
});
您的代碼無法編譯,但這是一個簡單的修復。 我假設g包含邊權重。 這里有一個錯誤:
if(g[n1.first][n2.second] < g[n2.first][n2.second])
它應該是
if(g[n1.first][n1.second] < g[n2.first][n2.second])
記住左邊第二個索引的名稱。 住在Coliru
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.