Search code examples
c++stlstl-algorithm

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.


Solution

  • 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.