c++ - 如何在 std::priority_queue 的仿函数中传输附加对象?

标签 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
    }
};

在 operator() 中应该被认为是 Other 类的任何对象。 如何将对象转换为仿函数? 我将仿函数用于 priority_queue。 Other 类的对象不能是静态字段。

还有其他方法吗?

最佳答案

制作Comparator存储 Other 类型的对象(或引用 shared_ptrunique_ptr 取决于所有权和有效性语义),并通过 Comparator 传递它的构造函数。

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;
};

创建 priority_queue 像这样,假设你想使用 vector<T>作为底层容器:

Other otherToHelpCompare;
Comparator myComparator{otherToHelpCompare};
std::priority_queue<T, std::vector<T>, Comparator> q{myComparator}; 

关于c++ - 如何在 std::priority_queue 的仿函数中传输附加对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967167/

相关文章:

c++模板类型推导在强制转换运算符中失败

c++ - 使用递归函数对 XML 树进行预序遍历?

c++ - 插入特定数据结构时我做错了什么?

Java:设计问题 - 集合之间的最小对

Go - 如果为空则等待优先级队列中的下一个项目

c++ - 有没有办法找出线程是否被阻塞?

data-structures - 哪个数据结构用于 "dynamic"优先级排队?

Haskell fmap 通过自定义数据类型

c++ - 与仿函数的函数组合 - 性能开销

c++ - 为什么这个示例有效?