![](/img/trans.png)
[英]priority_queue<vector<int> > pq; is saything that “priority_queue” is not a template, how would I fix this?
[英]How would i pop and push with this priority queue?
我正在嘗試對優先級隊列中的作業使用推送和彈出。 我該怎么辦? 我很好奇如何實現呢?
class Job
{
public:
int job_id;
string job_description;
int n_procs;
int n_ticks;
Job(int job_id, string job_description, int n_procs, int n_ticks);
Job(void);
~Job(void);
};
typedef vector<Job> Jobs;
typedef priority_queue<Job, Jobs, less<Job>> JobQueue;
優先級隊列類提供用於訪問隊列中元素的基本操作:
void std::priority_queue::push(const T &)
:將給定對象推入優先級隊列。 const T &std::priority_queue::top() const
:返回“ top”元素。 void std::priority_queue::pop();
:刪除“頂部”元素。 只需用Job
代替T
。
順便說一句:
我還沒有重載<運算符。 我認為優先級降低的隊列越少
在不知道如何比較的情況下,它將如何知道什么是“降序”? 所有std::less
所做的就是調用您定義的任何operator<
。 如果尚未定義operator<
,則std::less
將無法工作。
請參考此參考資料: http : //www.cplusplus.com/reference/stl/priority_queue/pop/
您還會發現此規范:
template < class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
這意味着(無需自己嘗試)您應該能夠:
JobQueue jq;
jq.push(Job(1,"one",0,1));
jq.push(Job(2,"two",2,3));
Job top = jq.pop()
請查看http://www.cplusplus.com/reference/stl/priority_queue的定義和示例
當您推送新作業時,將會有很多數據副本。 記住這一點。 您必須使運算符<對於Job過載,或者減少模板的專用性。
嘗試這個:
class Job
{
public:
int job_id;
string job_description;
int n_procs;
int n_ticks;
Job(int job_id, string job_description, int n_procs, int n_ticks);
Job(void);
~Job(void);
};
bool operator < (Job const& rhs, Job const& lhs)
{
return rhs.n_ticks < lhs.n_ticks;
}
typedef vector<Job> Jobs;
typedef priority_queue<Job, Jobs, less<Job>> JobQueue;
Job job(1,"job 1", 1,2);
JobQueue jobs;
jobs.push(job);
Job const& topJop = jobs.top();
//do whatever with topTob
//remove it from the queue
job.pop();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.