简体   繁体   English

在C ++中使用Comparator和构造函数上的参数的自定义类的优先级队列

[英]Priority Queue of custom Class using Comparator with argument on constructor in C++

I want to create a priority_queue of the class Edge in C++. 我想在C ++中创建Edge类的priority_queue

For that, I created the edgeCompare comparator class as follows: 为此,我创建了edgeCompare比较器类,如下所示:

class edgeCompare{
public:
    map<int, glm::mat4x4> * Qmap;

    edgeCompare(const map<int, glm::mat4x4> & Qm){
        * Qmap = Qm;
    }

    bool operator() (const Edge & e1, const Edge & e2) const{
        // code that compares and returns corresponding bool
        // OBS: in this function I use *Qmap
    }
}

The thing is, as you can see, that I need an external variable to do the comparison. 正如您所看到的,我需要一个外部变量来进行比较。

A priority_queue is usually declared as: priority_queue通常声明为:

priority_queue<Edge, vector<Edge>, edgeCompare> pq;

But in my case, I need to construct the edgeComparator with my variable Qmap . 但对我来说,我需要构造edgeComparator用我的变量Qmap

How should I proceed? 我该怎么办?

Thanks a lot! 非常感谢!

The template parameter is the type of the comparator. 模板参数是比较器的类型 You still need to pass an instance of the comparator to the priority_queue constructor, and that is when you can construct the comparator instance with whatever parameters you like. 您仍然需要将比较器的一个实例传递给priority_queue构造函数,这就是您可以使用任意参数构造比较器实例的时候。

For instance: 例如:

map<int, glm::mat4x4> m;
edgeCompare comp(m);
priority_queue<Edge, vector<Edge>, edgeCompare> pq(comp);

You can also create the edgeCompare object inline but extra parentheses are needed for disambiguation: 您还可edgeCompare联创建edgeCompare对象,但消除歧义需要额外的括号:

priority_queue<Edge, vector<Edge>, edgeCompare> pq((edgeCompare(m)));

Overload operator== , operator!= , operator> and operator< in the Edge class so that you can just compare them e1 == e2 in your comparator. Edge类中重载operator==operator!=operator>operator< ,以便您可以在比较器中比较它们e1 == e2

Also don't derive from std::map . 也不要从std::map派生。 It does not have a virtual destructor, which makes it a bad idea to derive from it. 它没有virtual析构函数,这使得从它派生出一个坏主意。

Just have your map as a private member to your class. 只需将您的地图作为班级的私人成员即可。

根据此链接 ,有一个重载允许您在priority_queue的构造函数中传入谓词。

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

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