Specifying sorting criteria in C + + at execution time

Source: Internet
Author: User

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 &AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.