c++ STL正确的参数priority_queue

c++ stl correct parameters to priority_queue

本文关键字:priority queue 参数 STL c++      更新时间:2023-10-16

下面是错误的代码片段

我想用c++的优先队列实现dijkstra。但我不能找出正确的语法使用这个优先级队列与边缘类。我想把边放到基于权重的priority_queue。

class edge{
public: 
    int src;
    int dest;
    int wt;
};
class comp {
bool operator() (int a, int b) {
    if(a<=b){
        return true;
    }else{
        return false;
    }
   }
};

priority_queue<int,edge,comp> check;
edge e1,e2,e3;
e1.dest=1;
e2.dest=2;
e3.dest=3;
#include <queue>
#include <iostream>
class edge{
public:
    int src;
    int dest;
    int wt;
};
struct less_weight {
    bool operator() (const edge& a, const edge& b) {
        return a.wt < b.wt;
    }
};
struct greater_weight {
    bool operator() (const edge& a, const edge& b) {
        return a.wt > b.wt;
    }
};
int main()
{
    std::priority_queue<int,std::vector<edge>,less_weight> prioritise_higher_weights;
    prioritise_higher_weights.push(edge{0, 1, 1 });
    prioritise_higher_weights.push(edge{1, 2, 2 });
    prioritise_higher_weights.push(edge{2, 3, 3 });
    std::priority_queue<int,std::vector<edge>,greater_weight> prioritise_lower_weights;
    prioritise_lower_weights.push(edge{0, 1, 1 });
    prioritise_lower_weights.push(edge{1, 2, 2 });
    prioritise_lower_weights.push(edge{2, 3, 3 });
    std::cout << prioritise_higher_weights.top().wt << std::endl;
    std::cout << prioritise_lower_weights.top().wt << std::endl;
}
预期输出:

3
1

注意优先级队列是如何按照给定谓词的逆排序的。

先读取priority_queue的规范。认真地读吧。

注意,第一个模板参数是你想要存储的类型,所以如果你想要存储Edge s,那么Edge应该是你的第一个参数。

第二个模板参数是priority_queue将在下面使用的容器,用于存储您提供的值。默认情况下,是std::vector,我认为对于演示目的来说已经足够好了。

第三个模板参数是比较器,用于比较将在队列中存储的值。由于您正在存储Edge s,因此需要一个能够比较Edge实例的比较器类,而不是int s。

如上所述,试试这个:

#include <vector>
#include <queue>
class Edge{
public:
    int src;
    int dest;
    int wt;
};
struct comp {
  // note the use of references
  bool operator() (const Edge& a, const Edge& b) {
    // comparison by edge weights
    return a.wt < b.wt;
  }
};
int main() {
  std::vector<Edge> storage;
  comp compare;
  std::priority_queue<Edge, std::vector<Edge>, comp> check(compare);
  Edge e1,e2,e3;
  e1.wt=1; e1.src=1; e1.dest=2;
  e2.wt=2; e2.src=1; e2.dest=2;
  e3.wt=3; e3.src=2; e3.dest=3;
  check.push(e1);
  // pushing the maximum in the middle, let's see where it gets
  check.push(e3);
  check.push(e2);
  // let's see what's on top
  const Edge& top=check.top();
  std::cout << "weight: "<< top.wt 
            << " src:" << top.src 
            << " dest:" << top.dest << std::endl; // got the maximum on top
}