Sorting a Queue of Structs

家住魔仙堡 提交于 2019-12-11 06:47:59

问题


I currently have a queue that holds a user specified number of structs called Process. Process is made up of a pid, burst, and arrival. I would like to sort the queue by arrival, but I don't have the faintest idea of where to begin. Here is some pseudocode to help illustrate what I'm trying to say:

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);
}

I'd be appreciative of anyone who could point me in right direction on how to do this, or if it is even possible. Thanks!


回答1:


Mostly you need to define operator< for your class:

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

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

Once you've done that, std::sort will work fine:

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



回答2:


You can sort using the standard library std::sort from the '' header. You can either provide a comparator or define an less operators.

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




回答3:


You should use std::priority_queue instead... Otherwise you'll have to sort the queue every time you push something onto it.

Note that you still need to define operator<




回答4:


You want to implement a calendar queue. Don't use the queue data structure for that but a 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;
}

There is no need to explicitly sort, the set will keep the contents sorted at all times and you can always remove the first by eraseing the begin() iterator.



来源:https://stackoverflow.com/questions/13280726/sorting-a-queue-of-structs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!