2012-11-08 171 views
1

我目前有一個隊列,它保存用戶指定數量的結構,稱爲進程。過程由一個pid,爆發和到達組成。我想在抵達時對隊列進行排序,但我並不知道從哪裏開始。下面是一些僞代碼來幫助說明什麼,我想說:對結構隊列排序

struct Process{ 
    int pid; 
    int burst; 
    int arrival; 
}; 

void function(int numProcesses){ 
    queue<Process> readyQueue; 

    // The following loop is a shortened version of my code 
    for(int i=0; i<numProcesses;i++){ 
     readyQueue.push(aProcess); 
    } 

    // This is where I need help! 
    // sort(readyQueue); 
} 

我會很感激的人誰可以點我在正確的方向上如何做到這一點,或者如果它甚至有可能的。謝謝!

回答

3

您可以使用標題中的標準庫std::sort進行排序。您可以提供比較器或定義較少的操作員。

struct Process{ 
    int pid; 
    int burst; 
    int arrival; 
}; 

    bool operator<(const Process& a, const Process& b) { 
      return a.arrival < b.arrival; 
    } 

    void function(int numProcesses){ 
     std::dequeue<Process> readyQueue; 

     // The following loop is a shortened version of my code 
     for(int i=0; i<numProcesses;i++){ 
      readyQueue.push_back(aProcess); 
     } 
     std::sort(readyQueue.begin(), readyQueue.end());  
    } 

http://en.cppreference.com/w/cpp/algorithm/sort

+0

他希望進程按到達順序排序 – billz

4

晴,你需要定義operator<爲類:

struct Process{ 
    int pid; 
    int burst; 
    int arrival; 

    bool operator<(Process const &other) { return arrival < other.arrival; } 
}; 

一旦你做到了這一點,std::sort將正常工作:

std::sort(std::begin(readyQueue), std::end(readyQueue)); 
+0

這正是我一直在尋找的!除了標準數組之外,我對它非常陌生。你能否解釋我會怎樣稱呼排序?請和非常感謝你。 –

+0

@Rick_Sch:我已經包含了一個示例調用到'std :: sort'。小問題:根據你使用的編譯器的年齡,你可能需要使用'readyQueue.begin()'而不是'std :: begin(readyQueue)'(對於'end'也是如此)。 –

+0

最後一件事(我希望):當我嘗試做readyQueue.begin()方法時出現這個錯誤:'error:'class std :: queue >''沒有名爲'begin'的成員,但是如果我嘗試begin(readyQueue)方法,我也會得到這個錯誤:''begin'沒有在這個範圍內聲明' –

0

你應該改爲使用std::priority_queue ...否則,你將不得不s每當你把東西推到上面的時候就排隊。

請注意,您還需要定義operator<

+0

我曾經想過這樣做,但是這個隊列只會被添加一次,所以優先隊列似乎不是必需的。 –

+1

查看[這個問題](http://stackoverflow.com/questions/3759112/whats-faster-inserting-into-a-priority-queue-or-sorting-retrospectively)辯論這些解決方案的優點速度明智。 – didierc

0

你想實現一個日曆隊列。不要使用該queue數據結構,而是一個set

struct Process{ 
    int pid; 
    int burst; 
    int arrival; 
    bool operator<(Process const& other) const { 
     if (arrival == other.arrival) { 
     if (pid == other.pid) 
      return this < &other; 
     return pid < other.pid; 
     } 
     return arrival < other.arrival; 
    } 
}; 

void func() { 
    std::set<Process> myQueue; 
} 

沒有必要明確地排序,該集將始終保持排序的內容,您可以通過erase荷蘭國際集團的總除去第一begin()迭代器。