infroz
infroz

Reputation: 1162

Issue with sorting algorithm and object pointers

I have an object containing some data such as:

class Employee{
    private:
         int employee_number;
         // +more objects and data
    public:
        int get_number() {
            return employee_number;
        }
};

The objects are stored in a pointer array:

Employee* employees[MAX + 1];

The first element in Employee is not used, so the algorithm skips employees[0]

The sorting algorithm is called each time a new employee has been added, here is what the sorting algorithm looks like:

int to = employees.length - 1;
for (int from = 1; from < to; from++) {
    if (employees[from]->get_number() > employees[from + 1]->get_number()) {
        Employee *tmp = employees[from + 1];
        int i = from;

        while (i >= 1 && employees[i]->get_number() > tmp->get_number()) {
            employees[i + 1] = employees[i];
            i--;
        }

        employees[i + 1] = tmp;
    }
}

I'm not sure why this doesn't sort the employees array, as this algorithm works well with regular int arrays. Also keep in mind my entire code is written in my own language, so I had to translate into English here.

Upvotes: 1

Views: 110

Answers (1)

jfMR
jfMR

Reputation: 24738

Assuming that you want to sort the Employee pointers in ascending order by the data member employee_number (i.e., employee_number is the key) of the objects they are pointing to, you could define the following predicate using a lambda expression:

auto cmp = [](auto a, auto b) {
   return a->get_number() < b->get_number();
};

Then, use the std::sort() algorithm with the predicate above:

auto begin = &employees[1]; // skip 1st element
std::sort(begin, employees + num, cmp);

where num above is 1 (since you said that the 1st entry is not used) plus the number of Employee pointers inserted so far.


I'm not really sure what you want to achieve, but if you have the intention of calling std::sort() on the array every time a new Employee is added to the array, you might want to consider using another container like std::set instead of an array.

Upvotes: 1

Related Questions