Hi, I want to sort an array of struct 'Workshops' in accordance with its member variable 'start_time'. I thought of using std::sort for the array and supplying 'CompareWorkshops' function as the third parameter-

bool CompareWorkshops(Workshops W1, Workshops W2)
{
    return (W1.start_time <= W2.start_time);
}
//calculate max no. of non-overlapping workshopes that can be attended at once
int CalculateMaxWorkshops(Available_Workshops* ptr)
{
    //to proceed, need to sort Workshops in accordance with their start_time
    sort(ptr->array.begin(), ptr->array.end(), CompareWorkshops);
    int i{ 0 }, count{ 0 }, previous_end{ 0 };
    do
    {
        if (ptr->array[i].start_time >= previous_end) {
            count += 1;
            previous_end += ptr->array[i].end_time;
        }
        i++;
    } while (i < ptr->n);
    return count;
}

But I get this error after supplying inputs through console-

Untitled.png

Is the error caused by sort() or something else?

Try passing a reference in your comparison function:

bool CompareWorkshops(const Workshops &W1, const Workshops &W2)

If that doesn't work, I'd need to see more of the code. You should also try stepping through the code in the debugger.

@nullptr still got the same error. here's the full program- https://1drv.ms/u/s!Av4KGJ7KdNvGhz2UmZCfYsEhtQrW
Just to inform, the "main()" function is locked out, and I'm only allowed to modify other functions.

This compiles and runs fine with gcc compiler. I'd suggest stepping through with the debugger to find where the error is triggered. Hopefully someone with MS VC++ may chime in.

commented: couldn't resolve the issue with sort() and CompareWorkshops(), but tried overloading 'operator<' instead which worked. thanks anyway! +0

The answer to your original problem is fairly simple. The comparator that you pass to sort must promote weak ordering. By comparing using <= you're promotiong strong ordering and this makes the compiler fail. Removing the = fixes it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.