// Recently, I have encountered such a problem: // There are more than a dozen member data in a class, I need to provide different sorting methods according to different members. As follows:
Class Cell {public: string name; string time; int tchdrop; double traffic; // more ...};
// Recently, STL is being learned, so I want to combine the knowledge you have learned, design a general method, just mention // for the members of the members and sorting criteria (ie, the function object), can // with the STL algorithm Match, sorted, compare, compare, etc.
Template
/ / Compare the member BOOL Operator () (Const C & A, Const C & B) const {return m_pred (a. * M_pmd, b. * M_pmd);};
Private: t (c :: * m_pmd); // class member pointer PRED M_PRED; / / comparison function};
/ / 照 照 照 照 照 形 形 形 形 形 形 形 形 形 形RETURN COMP_MEM_DATA
// The following can be started .// sort (vcell.begin (), vcell.end (), comper_mem_data (& cell :: name)); // sort (vCell.begin (), vcell.end (), COMPER_MEM_DATA (& Cell :: Traffic, Greater
// The following is the test program is passed in BCB5.5, MSVC6.0.
#include
Inline Ostream & Operator << (Ostream & Out, Const Cell & Cell) {OUT << Cell.Name << "| << Cell.Time <<" | << Cell.tchdrop << "| << Cell.Traft << "|" // more ... << end1; return out;} template INT main () {Vector Sort (vcell.begin (), vcell.end (), comper_mem_data (& cell :: tchdrop); Output (vCell); sort (vcell.begin (), vcell.end (), Comper_Mem_Data (& Cell :: Traffic, Greater Vector CHAR LC; CIN >> LC; RETURN 0;} The output of the program is as follows: / * Cell Name | TIME | TCHDROP | TrafficA | 3 | 2 | 47.0168 | C | 1 | 2 | 66.5151 | D | 5 | 19 | 86.5017 | F | 9 | 23 | 11.1087 | | 5 | 78 | 75.7897 | G | 7 | 84 | 54.2253 | H | 7 | 88 | 61.1774 | I | 1 | 90 | 59.2578 | J | 3 | 94 | 89.9625 | B | 6 | 99 | 89.2514 | Cell Name | TIME | TCHDROP | TrafficJ | 3 | 94 | 89.9625 | B | 6 | 99 | 89.2514 | D | 5 | 19 | 86.5017 | E | 5 | 78 | 75.7897 | C | 1 | 2 | 66.5151 | H | 7 | 88 | 61.1774 | I | 1 | 90 | 59.2578 | G | 7 | 84 | 54.2253 | A | 54.2253 | A | 3 | 2 | 47.0168 | F | 9 | 23 | 11.1087 | Cl IS Find // /// Use the same method, Produces generic classes that compare two class member functions return values, // class data members are compared with the same type of constant parameters. // This is not listed here. // The above improper, please also ask prawns to advice.