jeudi 4 avril 2019

C++: How to sort a vector of objects derived from class using one of its parameters

I'm trying to sort a vector of objects, created from a class in the project.

I have two classes - Playlist and ListIndex, that inherits from a List_base class. In the List_base class, I want to sort a vector of objects (either Playlist or ListIndex) by their name. the name property is defined in the List_base class. I tried using struct or function that compares the name field and pass it to the sort function. I'm getting all kinds of errors. I'm new to C++ and stuck in this error for a very long time

The List_base sort method with the compare function

//the function should be able to get either Playlist vector
// or ListIndex vector (both inherits from List_base)
void List_base::sortList(vector<List_base> data) {
    sort(data.begin(), data.end(), compFunc());
}

bool List_base::compFunc(List_base *a, List_base *b) {
    return a->getName().compare(b->getName()) > 0;
}

The name field is declared in the List_base class:

class List_base
{
    public:
        List_base(string name);
        string getName();
        void sortList(vector<List_base> data);
        virtual ~List_base();

    protected:

    private:
        string name;
        bool compFunc(List_base *a, List_base *b);
};

What am I doing wrong? I can't even focus on a specific error. I've also tried casting but failed there too

pls, help!

Aucun commentaire:

Enregistrer un commentaire