C++ sort排序函数用法详解

  // sort algorithm example

  #include     // std::cout

  #include    // std::sort

  #include       // std::vector

  bool myfunction (int i,int j) { return (i

  bool myfunction2 (int i,int j) { return (i>j); }//降序排列

  struct myclass {

  bool operator() (int i,int j) { return (i

  } myobject;

  int main () {

  int myints[8] = {32,71,12,45,26,80,53,33};

  std::vector myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):

  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp

  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  //std::sort (myints,myints+8,myfunction);不用vector的用法

  // using object as comp

  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:

  std::cout << "myvector contains:";

  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)//输出

  std::cout << ' ' << *it;

  std::cout << '

  ';

  return 0;

  }