[英]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.