提问者:小点点

具有自定义比较器的优先级队列


我正在尝试使用优先级队列来保存使用以下成员变量反对的自定义:

class Jobs{
    string id;
    string location;
    int start;
    int end;
};

我将从文件中读取工作ID和工作权重的哈希图。我最终会有一个

unordered_map<string, int> jobWeight;

持有这些信息。我想最终将工作列表推送到priority_queue,优先级基于hashmap jobWeight。权重最高的工作应该排在第一位。

参考其他教程,我注意到你应该创建一个单独的类/结构并实现运算符()。然后你会将这个比较类传入priority_queue参数。但是,priority_queue似乎使用默认参数创建了这个比较器类的新实例?我如何能够从这个比较器类中引用我的jobWeight hashmap?

class CompareJobs{

    map<string, int> jobWeight;

public:

    CompareJobs(map<string, int> &jobWeight){
        jobWeight = jobWeight;
    }

    bool operator () (const Jobs &a, const Jobs &b){

        return jobWeight.find(a)->second < jobWeight.find(b)->second;

    }

};

共2个答案

匿名用户

如何从这个比较器类中引用我的jobWeight hashmap?

添加一个对映射的引用到你的Compare类!当然,你需要确保这个引用保持有效。你不能使用普通引用(因为它们不能复制,你的Compare类必须是这样),而是可以使用std::reference_wrapper

using IDMap = std::unordered_map<std::string, int>;

struct JobsByWeight {
  std::reference_wrapper<IDMap const> weights_ref;
  bool operator()(Job const & lhs, Job const & rhs) const {
    auto const & weights = weights_ref.get();
    auto lhsmapping = weights.find(lhs.id);
    auto rhsmapping = weights.find(rhs.id);
    if (lhsmapping == weights.end() || rhsmapping == weights.end()) {
      std::cerr << "damn it!" << std::endl;
      std::exit(1);
    }
    return lhsmapping->second < rhsmapping->second;
  }
};

然后只需将Compare类的一个对象传递给优先级队列的构造函数(链接中的overload(1)):

std::priority_queue<Job, std::vector<Job>, JobsByWeight> queue{std::cref(that_id_map)};

由于没有构造函数允许您在队列中移动Compare类,因此您确实需要JobByWeight中的引用。否则会有您的地图副本(正如您所说,这可能很大)。

注意:未经测试的代码。

匿名用户

std::priority_queue的默认构造函数实际上采用可选参数:

explicit priority_queue(const Compare& x = Compare(), Container&& = Container());

您会注意到第一个参数是比较器类的实例。

首先构造您的比较器类,使其以您方便的任何方式引用您的hashmap,然后使用比较器类来构造您的优先级队列。