2012-08-22 95 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