问题
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