首页 > 解决方案 > 在 C++ 中对对象数组进行排序

问题描述

我是新手,这是我的第一个问题。所以我正在为一个任务组织者工作,我想按任务的“紧迫性”值来组织任务列表。这是我的代码:

#include <iostream>
#include <math.h>
#include <vector>
#include <stdlib.h>
#include <list>

using namespace std;

struct Task {
public:
    string name;
    float deadline, estimated;
    int urgency;
    int getUrgency() {
        urgency = ceil(deadline - estimated);
        return urgency;
    }
};

void newTask(Task task[], int n1) {
    for (int i = 0; i < n1; i++)
    {
        system("cls");
        cout << "Input task name: ";
        cin >> task[i].name;
        cout << "Input task deadline (in hours): ";
        cin >> task[i].deadline;
        cout << "Input task estimated work time (in hours): ";
        cin >> task[i].estimated;
    }
}

void printAll(Task task[], int n1) {
    system("cls");
    cout << "Name\tDeadline\tEstimated\tUrgency\n";
    for (int i = 0; i < n1; i++)
    {
        cout << task[i].name << "\t" << task[i].deadline << "\t\t" << task[i].estimated << "\t\t" << task[i].getUrgency() << endl;
    }
}

int main() {
    int n;
    cout << "How many work do you have? ";
    cin >> n;
    //Create number of object based on input n
    std::vector<Task> p(n);
    newTask(p.data(), n);
    std::list<Task> taskList;
    printAll(p.data(), n);
    cin.ignore();
    return 0;
}

我想添加一个按“紧急”值对任务列表进行排序的函数。我应该使用什么样的功能?

标签: c++arrayssorting

解决方案


在您的情况下,您可以在定义自定义比较函数的向量上使用std::sort标题中定义的函数<algorithm>p

std::sort (p.begin(), p.end(), sortTaskByUrgency);

其中sortTaskByUrgency()定义为:

bool sortTaskByUrgency(const Task& lhs, const Task& rhs)
{
    return lhs.getUrgency() < rhs.getUrgency();
}

在示例代码中使用上述函数getUrgency()必须是const

int getUrgency() const { return ceil(deadline - estimated); }

删除无用int urgency的公共成员。


推荐阅读