Understanding how struct works

Hello! The following excerpt is from
http://www.cplusplus.com/reference/algorithm/sort/

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.

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

1
2
3
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

1
2
3
4
 bool operator < (const Student& s) const {
    compareCount++;
    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.