Delivery of a C + + sort class Member

Source: Internet
Author: User

The sort method is provided in the C + + template, which generally has two methods: passing a function and passing an object.

The first method: function

bool Compare (conststringconststring &strright) {  return strleft<strright;} int main () {vector<string> vtstrtest;      Vtstrtest.push_back (...);  Std::sort (Vtstrtest.begin (), vtstrtest.end (), compare);  return0;}

Note: The Compare function here is a global function, not a member function.

The second method of

The code is as follows:

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<iostream>#include<vector>#include<algorithm>using namespacestd;classsorttest{ Public: Sorttest () {}voidrun () {vtsort (); }Private:    voidVtsort (); structSortdesc {BOOL operator() (Const string&left,Const string&Right ) {            returnLeft >Right ; }    };};voidsorttest::vtsort () {vector<string>vttemp; Vttemp.push_back ("ABCEF"); Vttemp.push_back ("12348"); Vttemp.push_back ("$#@!");    Std::sort (Vttemp.begin (), Vttemp.end (), Sortdesc ());  for(inti =0; I<vttemp.size (); ++i) {cout<<vtTemp[i]<<Endl; }}intMain () {sorttest test;    Test.run (); return 0;}

The running result of the above code:

Abcef
12348
$#@!

Note that it is not possible to sort a member function pointer in a class, but rather to pass an object. Because the C + + template gets no member function pointers to the class, the type member function pointers all imply the this pointer.

Delivery of a C + + sort class Member

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.