Home > Mobile >  Sorting array of objects in c
Sorting array of objects in c

Time:09-25

I'm a newbie and this is my first question. So I am working for a task organizer and I want to organize list of tasks by their "urgency" value. Here is my code:

#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;
}

I want to add a function that sorts the list of tasks by their "urgency" value. What kind of function should I use?

CodePudding user response:

I would try using std::sort. It will sort in place any iterable object (array, vector, etc...). A common std::sort function call has the following arguments: The first argument is an iterator/pointer to the beginning of the collection, the second argument is an iterator/pointer to the end of that same collection, and the third argument is a function callback that determines how the data is sorted. You can see an example implementation here

CodePudding user response:

In your case you can use the std::sort function on the p vector defining a custom compare function:

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

where sortTaskByUrgency() is defined as:

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