// This file is one of a series that demonstrates how to write & use // a comparison functor for an STL container. // // This version does a multi-level sort on an array of structures. #include #include #include #include #include #include using namespace std; struct student { int id; string name; float gpa; }; struct compare { // Primary sort: descending order by gpa // Secondary sort: ascending by student id bool operator()(const student &a, const student &b) const { if (a.gpa != b.gpa) return a.gpa > b.gpa; return a.id < b.id; } }; int main() { student roster[] = { {81234567, "Jack Applin", 3.999999}, {84444444, "Joe Kolledge", 2.2}, {83333333, "Homecoming Queen", 2.2}, {80000000, "Darrell Whitley", 1.0}, }; typedef set con; con s(roster, roster+4); for (con::iterator i=s.begin(); i!=s.end(); i++) cout << i->id << ' ' << left << setw(18) << i->name << fixed << setprecision(2) << i->gpa << '\n'; }