C++ 如何在std::priority_队列的functor中传输附加对象?
我有我的结构:C++ 如何在std::priority_队列的functor中传输附加对象?,c++,priority-queue,functor,C++,Priority Queue,Functor,我有我的结构: struct S{ int a; }; 我有课: class Other{ //some fields }; 我需要写函子: struct Comparator { bool operator()(S& l, S& r) { //some code, considered l,r and any object of class Other } }; In运算符()应被视为其他类的任何对象。 如何将对象转换为函
struct S{
int a;
};
我有课:
class Other{
//some fields
};
我需要写函子:
struct Comparator {
bool operator()(S& l, S& r) {
//some code, considered l,r and any object of class Other
}
};
In运算符()应被视为其他类的任何对象。
如何将对象转换为函子?
我对优先级队列使用函子。
类Other的对象不能是静态字段
实现此目的的另一种方法是使
比较器
存储类型为其他
的对象(或引用、共享的
或唯一的
,具体取决于所有权和有效性语义),并通过比较器
的构造函数传入
struct Comparator {
Comparator(const Other& val) : mVal(val){}
bool operator()(S& l, S& r)
{
//Comparison code here uses l, r and mVal
}
private:
Other mVal;
};
假设您希望使用vector
作为底层容器,则可以这样创建:
Other otherToHelpCompare;
Comparator myComparator{otherToHelpCompare};
std::priority_queue<T, std::vector<T>, Comparator> q{myComparator};
其他帮助比较;
Comparator myComparator{otherToHelpCompare};
std::priority_queue q{myComparator};
需要更多信息吗