2012-08-22 93 views
1

我正在使用std :: priority_queue第一次进行大学任务。该任务是对进程调度的模拟。我想传递一个参数给我的比较结构构造函数来初始化,我想我在另一个论坛上看到了它,但我无法再次找到源代码。我在发帖前看过,但没有看到类似的东西。std :: priority_queue参数化比较结构

这里是我的priority_queue:

/* schedules.hpp/.cpp */ 
#include "process.hpp" 

namespace my = procschedassignment; 

int tick = 0; 
std::priority_queue<my::Process, _ 
     std::vector<my::Process>, 
     PrioritiseHighestResponseRatioNext(tick) > rq; 
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
line 100 - compiler errors are here 
// ... 

这是我比较结构:

/* prioritise_process.hpp/.cpp */ 
#include "process.hpp" 

namespace my = procschedassignment; 

struct PrioritiseHighestResponseRatioNext { 
    public: 
     explicit PrioritiseHighestResponseRatioNext(int const& cpu_time) 
       : cpu_time_(cpu_time) {}; 
     bool PrioritiseHighestResponseRatioNext::operator()(my::Process const& lhs, 
       my::Process const& rhs) { 
      bool ret; 

      if (lhs.wait_time() > cpu_time_) { 
       ret = (lhs.ResponseRatio() > rhs.ResponseRatio()); 
      } else if (rhs.wait_time() > cpu_time_) { 
       ret = (lhs.ResponseRatio() < rhs.ResponseRatio()); 
      } 

      return ret; 
     }; 

    private: 
     const int cpu_time_; 
}; 

编译器错误,我用这个代码得到的是:

../src/schedules.cpp:100: error: ‘time’ cannot appear in a constant-expression 
../src/schedules.cpp:100: error: template argument 3 is invalid 
../src/schedules.cpp:100: error: invalid type in declaration before ‘;’ token 

是否有可能有一个参数化的比较结构与std :: priority_queue? 我是STL新手,所以我很抱歉,我对这里发生的事情没有更好的理解。

+0

另请注意,如果'lhs.wait_time'等于'cpu_time_'和'rgs.wait_time()'''ret'变量未初始化并且将具有垃圾值。 – fasked

+0

@fasked是的,谢谢:)我发誓,它只是在尝试寻找解决方案时重写某些代码块的结果。 – ItsOnlyOneLineOfCode

回答

3

您试图将对象作为模板参数传递。这不起作用。您应该将您的比较器作为参数提供给构造函数,并将比较器的类型作为模板参数提供。

// declare type 
typedef std::priority_queue<my::Process, 
          std::vector<my::Process>, 
          PrioritiseHighestResponseRatioNext > process_queue; 
          // ^^^ just a type, no object ^^^ 
// create object 
process_queue rq(PrioritiseHighestResponseRatioNext(tick)); 
+0

我明白了,但我永远不会想到我自己。起初我不明白你做了什么,所以我咨询了http://www.cplusplus.com/reference/stl/priority_queue/priority_queue/,我认为它现在是有道理的。很酷。 – ItsOnlyOneLineOfCode