Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 323
kladd Avatar asked Apr 27 '26 19:04

kladd


1 Answers

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.

like image 96
Kerrek SB Avatar answered Apr 29 '26 11:04

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!