Search code examples
c++sortingdeque

Easy fix - sorting a deque on multiple values


I'm trying to figure out how to sort a deque of structs on two values, not just one. The code I have is what I have which perfectly sorts on arrival, but if two items came in with the same pid, I'd like them to be in pid order as well. I hope I'm making sense!

For example:

A process that has a pid of 1 and an arrival of 10 should be before a process with pid of 2 with an arrival of 10, even if the process with pid 1 comes later in the deque originally.

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

int sortOnArrival (Process const &a, Process const &b){
    return a.arrival < b.arrival;
}

int main(int argc, char *argv[]){

    deque<Process> readyQueue;

    // This is just pseudocode, but trust me, it works. :)
    fill(readyQueue);

    sort(readyQueue.begin(), readyQueue.end(), sortOnArrival);
}

Solution

  • Just use a suitable comparison object. For example, you could use

    struct sortOnPidAndArrival {
        bool operator()(Process const& p0, Process const& p1) const {
            return std::tie(p0.pid, p0.arrival) < std::tie(p1.pid, p1.arrival);
        }
    };
    

    In case you wonder why I'm using a function object rather than a function pointer: The code in this function object can entirely be inlined. The call through a function pointer cannot.