将 std::sort 与自定义 class 一起使用时出现问题

Problem using std::sort with custom class

做 hackerrank 问题“参加研讨会”https://www.hackerrank.com/challenges/attending-workshops/problem

我遇到无法对矢量进行排序的问题。我尝试使用 lambda(在评论中),然后重载运算符 >.

我的向量从来没有被排序过。你能帮我找出我做错了什么吗?这是我的代码:

#include<bits/stdc++.h>

using namespace std;

//*************ABOVE IS LOCKED CODE BY HACKERRANK****************;
//Define the structs Workshops and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop
{
    int startTime;
    int endTime;
    int duration;
    Workshop(){}
    Workshop(int pStartTime, int pDuration)
    :startTime(pStartTime), duration(pDuration)
    {
        endTime = startTime + duration;
    }
    bool operator < (const Workshop &other) const
    {        
        cout << "trace inside operator never showing up" << endl;
        return endTime < other.endTime;
    }
};

struct Available_Workshops
{
    int nbWorkshop;
    vector<Workshop> workshops;
    Available_Workshops(int *start_times, int *durations, int n)
    :nbWorkshop(n)
    {
        workshops.reserve(n);
        for(int i = 0; i < n; ++i)
        {
            workshops[i] = Workshop(start_times[i], durations[i]);
        }
    }    
};

Available_Workshops *initialize(int *start_time, int *duration, int n)
{
    return new Available_Workshops(start_time, duration, n);        
}

int CalculateMaxWorkshops(Available_Workshops *avai_work_ptr)
{   
    //The two for loops are just there to trace the content of avai_work_ptr->nbWorkshop to validate sorting...
    for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
        cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
    
    std::sort(avai_work_ptr->workshops.begin(), avai_work_ptr->workshops.end());//, [](const Workshop &a, const Workshop &b){cout << "compar"; return a.startTime < b.startTime;});

    for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
        cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;

    int maxWorkshop = 0;
    //Chunk of code removed because it is not related to the sort problem...        
    //...
    return maxWorkshop;
}
//*************BELOW IS LOCKED CODE BY HACKERRANK****************;
int main(int argc, char *argv[]) {
    int n; // number of workshops
    cin >> n;
    // create arrays of unknown size n
    int* start_time = new int[n];
    int* duration = new int[n];

    for(int i=0; i < n; i++){
        cin >> start_time[i];
    }
    for(int i = 0; i < n; i++){
        cin >> duration[i];
    }

    Available_Workshops * ptr;
    ptr = initialize(start_time,duration, n);
    cout << CalculateMaxWorkshops(ptr) << endl;
    return 0;
}

谢谢。

        workshops.reserve(n);

错了。它只是进行分配而不增加有效元素的数量,因此 end() 迭代器仍将位于数组的顶部。

你应该使用

        workshops.resize(n);

相反。