kladd
kladd

Reputation: 159

STL-Sort not working as expected

I feel as though I'm using this correctly but the compiler feels otherwise. I'm trying to sort a list of courses in alphabetical order in my sort_by_name function using the stl sort algorithm. This is roughly what I've written:

class SomeClass {
  private:
    struct course {
        string id, name;
    };
    vector<course> COURSES;
    bool nameCmp(course a, course b) {return (a.name > b.name) ? true : false;}
  public:
    void sort_by_name() {
        sort(COURSES.begin(), COURSES.end(), nameCmp);
    }
};

Error:

error: no matching function for call to ‘sort(std::vector<SomeClass::course>::iterator, std::vector<SomeClass::course>::iterator, <unresolved overloaded function type>)’

Thanks in advance for any help.

Upvotes: 2

Views: 1636

Answers (3)

eduffy
eduffy

Reputation: 40224

     bool SomeClass::nameCmp(course a, course b) {return (a.name > b.name) ? true : false;}

Has an implicit SomeClass *this parameter. Make the method outside the class by either moving the declaration or making it static.

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308206

The sort algorithm isn't going to call the nameCmp function from an object or in relation to the class, it's going to call it from the global namespace. You need to make it a free function, or make it static and use SomeClass::nameCmp.

Upvotes: -1

Kerrek SB
Kerrek SB

Reputation: 477110

Change the function to this:

static bool nameCmp(course a, course b) { return a.name > b.name; }

Even better would be to pass the arguments by const-reference, course const & a etc.

Upvotes: 8

Related Questions