优先级队列与自定义比较器

时间:2016-09-18 23:34:50

标签: c++ c++11 priority-queue

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

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

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

unordered_map<string, int> jobWeight;

持有此信息。我想最终将一个Jobs列表推送到priority_queue,优先级基于hashmap jobWeight。最高加权的工作应该是第一位的。

参考其他教程,我注意到你应该创建一个单独的类/结构并实现operator()。然后,您将此比较类传递给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 个答案:

答案 0 :(得分:2)

npm install -g ionic @1.x ionic start myApp tabs cd myApp ionic platform add android ionic build android. 的默认构造函数实际上是可选参数:

std::priority_queue

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

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

答案 1 :(得分: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类的对象传递给priority queue's constructor(链接中的(1)过载):

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

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

注意:未经测试的代码。

相关问题