Understanding how struct works

Hello! The following excerpt is from

struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;

My question is: what is myobject going to do? I understand structs are like classes except that structs are public whereas classes are private.

myobject is an old-style functor. Here, since the () operator is overloaded, you can call 'myobject' like it was a function:

bool compare = myobject(3,5);

// here, 'compare' will be true, because 3<5 

std::sort uses this as a mechanism where you can define how objects are to be ordered. It will take 'myobject' as a parameter and will "call it" (really, it will call the () operator) for elements in order to sort them.

std::sort (myvector.begin(), myvector.end(), myobject);  // <- myobject is used as the functor here 
Thank you! I'm writing a Student class with functions that sort student IDs, and I want to keep track of the number of comparisons. So I have

 bool operator < (const Student& s) const {
    return studentID < s.studentID;

When I call the sort algorithm, can I just type

sort (list.begin(), list.end(), <);

? Thanks!
Not quite.

If you don't give a functor, sort will use the < operator by default. So if you are overloading the < operator, it's even simpler:

sort( list.begin(), list.end() );
Topic archived. No new replies allowed.