1 //functor that defines the collation criteria2template<classT>3 classruntimecmp4 {5 Public:6 enumCmp_mode {_normal, _reverse};7 Public:8RUNTIMECMP (Cmp_mode m =_normal): Mode (m) {}9 Ten BOOL operator() (ConstT &t1,ConstT &t2)Const{returnmode = = _normal? T1 < T2:t2 <T1;} // overload () operator One BOOL operator== (Construntimecmp &RC) {returnmode = =Rc.mode;} A - Private: - cmp_mode mode; the }; - - intMain () - { +typedefSet<int, runtimecmp<int> >Intset; - Intset coll1; +Coll1.insert (4); AColl1.insert (7); atColl1.insert (5); -Coll1.insert (1); -Coll1.insert (6); -Coll1.insert (2); -Coll1.insert (5); -cout <<"coll1:"; inCopy (Coll1.begin (), Coll1.end (), ostream_iterator<int> (cout," ")); -cout <<Endl; to +runtimecmp<int> Reverse_order (runtimecmp<int>:: _reverse); - the intset coll2 (reverse_order); *Coll2.insert (4); $Coll2.insert (7);Panax NotoginsengColl2.insert (5); -Coll2.insert (1); theColl2.insert (6); +Coll2.insert (2); AColl2.insert (5); the +cout <<"coll2:"; -Copy (Coll2.begin (), Coll2.end (), ostream_iterator<int> (cout," ")); $cout <<Endl; $ -COLL1 =coll2; -Coll1.insert (3); thecout <<"coll1:"; -Copy (Coll1.begin (), Coll1.end (), ostream_iterator<int> (cout," "));Wuyicout <<Endl; the - //test whether the coll1 and coll2 sorting criteria are the same Wu if(Coll1.value_comp () = =Coll2.value_comp ()) - { Aboutcout <<"Coll1 and coll2 have same sorting criterion"<<Endl; $ } - Else - { -cout <<"Coll1 and coll2 have different sorting criterion"<<Endl; A}
Program output:
Coll1:1 2 4 5 6 7
Coll2:7 6 5 4 2 1
Coll1:7 6 5 4 3 2 1
Coll1 and coll2 have same sorting criterion
Note: The assignment operator also assigns the sorting criteria
See standard C + + library
Specifying sorting criteria in C + + at execution time