C++中顶点的队列

Queue of vertex in C++

本文关键字:队列 顶点 C++      更新时间:2023-10-16

我想实现Dijkstra算法,并且非常需要将顶点存储在队列中。

#include <iostream>
#include <queue>
using namespace std;
int main ()
{
priority_queue<int> mypq;//I want to put a pointer to vertex instead of int
mypq.push(10);//Here I want to push vertex 
mypq.push(20);
mypq.push(15);
cout << "mypq.top() is now " << mypq.top() << endl; 
return 0;
}

阅读评论部分。

需要记住的主要一点是,priority_queue是一个已排序的容器,因此它要求您为要存储的对象定义一个比较(必须遵循严格的弱排序)。

既然你谈到了Dijkstra的算法,让我们假设每个顶点都有一个权重,我们希望顶点按照这些权重排序。

struct vertex { 
    int x, y;
    unsigned weight;
    vertex(int x, int y, unsigned weight) : x(x), y(y), weight(weight) {}
    bool operator <(vertex &other) { return weight < other.weight; }
};

现在,顶点对象的优先级队列非常简单:

std::priority_queue<vertex> vertices;
vertices.push(vertex(1, 2, 3));
vertices.push(vertex(0, 1, 2));
vertices.push(vertex(10, 11, 12));
std::cout << "Top = " << vertices.top() << "n";

编辑:您需要为最后一行定义一个插入运算符才能工作——类似于:

std::ostream &operator<<(std::ostream &os, vertex const &v) { 
    return os << "(" << v.x << ", " << v.y << '[' v.weight << "])n";
}