在变量上排序标准结构数组 [英] Sorting a standard array of structs on a variable

查看:168
本文介绍了在变量上排序标准结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

c ++ sort with structs





我试图找出如何在数组中保存的结构体中的特定变量上对结构体数组进行排序。这是我的代码:

I am trying to figure out how to sort an array of structs on a specific variable in the struct held within the 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! :)
}



我真的想能够在我的代码中排序数组到达时间。我已经简化了我的代码,给你一个大致的想法,我想要完成的。在我的实际代码中,数组是从文件读入的信息动态填充的。 我知道使用列表或者甚至是Vector都是更好的选择,但我决心使用数组来确定。

任何帮助与排序这将不胜感激! :)

Any help with sorting this would be appreciated! :)

推荐答案

使用 >< algorithm> header:

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

这篇关于在变量上排序标准结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆