对结构队列进行排序 [英] Sorting a Queue of Structs
问题描述
我目前有一个队列,其中包含用户指定数量的名为 Process 的结构.进程由pid、burst和到达组成.我想按到达对队列进行排序,但我不知道从哪里开始.下面是一些伪代码来帮助说明我想说的内容:
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!
推荐答案
大多数情况下,您需要为您的类定义 operator<
:
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; }
};
一旦你这样做了,std::sort
就可以正常工作了:
Once you've done that, std::sort
will work fine:
std::sort(std::begin(readyQueue), std::end(readyQueue));
这篇关于对结构队列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!