תשובה
בעיקרון sort ממין ע"פ אופרטור =>. ניתן לספק פרמטר נוסף לפונקציה שיהיה עצם של מחלקה אשר לה מוגדר אופרטור () אשר מקבל שני פרמטרים מסוג האיברים בוקטור (זה נקרא function object). למשל בדוגמא המצורפת הגדרתי מחלקה פשוטה עם שדה יחיד של int + פונקציות. הגדרת שתי מחלקות להשוואה המשתמשות בפונקציה של המחלקה, מחלקה אחת למיון בסדר עולה ואחת למיון בסדר יורד. תסתכל על הדוגמא (מצורף גם כקובץ) ואם יש לך עוד שאלות אני אשמח לעזור.
#include <algo.h> #include <vector> #include <iostream.h> class A { private: int v; public: A(int v1) : v(v1) {} A(const A& other) : v(other.v) {} A& operator = (const A& other) { v = other.v; return *this; } int getV() const { return v; } bool big(const A& other) const { return v >= other.v; } bool small(const A& other) const { return v <= other.v; } }; ostream& operator << (ostream& os,const A& a) { return os << a.getV() ; } class LessEqThan { public: bool operator() (const A& a1,const A& a2) { return a1.small(a2); } }; class GreatEqThan { public: bool operator() (const A& a1,const A& a2) { return a1.big(a2); } }; int main() { std::vector<A> vec; vec.push_back(A(4)); vec.push_back(A(2)); vec.push_back(A(1)); vec.push_back(A(3)); cout << "Before sorting "; copy(vec.begin(), vec.end(), ostream_iterator<A>(cout, " ")); cout << endl; sort(vec.begin(),vec.end(),LessEqThan()); cout << "After sorting (increasing)"; copy(vec.begin(), vec.end(), ostream_iterator<A>(cout, " ")); cout << endl; sort(vec.begin(),vec.end(),GreatEqThan()); cout << "After sorting ( decreasing)"; copy(vec.begin(), vec.end(), ostream_iterator<A>(cout, " ")); cout << endl; return 0; }