Sort a standard array of structures for a variable

Possible duplicate:
C ++ sort with structs

I am trying to figure out how to sort an array of structures in a specific variable in a structure stored in an array. Here is my code:

struct Process{ int pid; int burst; int arrival; }; int main(int argc, char *argv[]){ // The number of processes int numProcesses = 3; //Create an array that holds 10 Process structs Process *arrayOfProcesses = new Process[numProcesses]; // Puts values in each pid, burst, and arrival arrayOfProcesses[0].pid = 0; arrayOfProcesses[0].burst = 8; arrayOfProcesses[0].arrival = 2; arrayOfProcesses[1].pid = 1; arrayOfProcesses[1].burst = 12; arrayOfProcesses[1].arrival = 3; arrayOfProcesses[2].pid = 2; arrayOfProcesses[2].burst = 4; arrayOfProcesses[2].arrival = 1; // Sort the array based on the arrival time // Help! :) } 

I would really like to be able to sort the array in my code by arrival time. I simplified my code to give you a general idea of ​​what I'm trying to accomplish. In my actual code, the array array is populated dynamically from the information read by the file. I know that using a list or even a vector would be a better option, but I decided to deal with arrays.

Any help in sorting would be appreciated! :)

+4
source share
2 answers

Use sort from the standard <algorithm> header:

 std::sort(arrayOfProcesses, arrayOfProcesses+numProcesses, [](Process const &a, Process const &b){ return a.arrival < b.arrival; }); 
+4
source

You can use your array with the STL sorting algorithm by adding a comparison function:

 #include <algorithm> bool operator<(const Process& lhs, const Process& rhs) { return lhs.pid < rhs.pid; } sort(arrayOfProcesses, arrayOfProcesses + numProcesses); 
+3
source

Source: https://habr.com/ru/post/1444522/


All Articles