天天看点

c++中的sort 排序函数 less和greater使用

http://www.cplusplus.com/reference/functional/less/

http://www.cplusplus.com/reference/algorithm/sort/?kw=sort

c++中的sort 排序函数

  1. 默认排序,从小到大
template <class RandomAccessIterator>
  void sort (RandomAccessIterator first, RandomAccessIterator last);
           
  1. 通过第三个参数来执行排序(从小到大或者从大到小)
template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
           
// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j){ return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {,,,,,,,};
  std::vector<int> my_vector (myints, myints+);           
  // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (my_vector.begin(), my_vector.begin()+);   
  //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (my_vector.begin()+, my_vector.end(), myfunction); 
  // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (my_vector.begin(), my_vector.end(), myobject);     
  //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "my_vector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
  std::cout << ' ' << *it;
  std::cout << '\n';

  return ;
}
           
my_vector contains:        
           

另外,c++中提供了比较函数,就不需要我们来重新写比较函数了

less<type>()    //从小到大排序 <
grater<type>()  //从大到小排序 >
less_equal<type>()  //  <=
gtater_equal<type>()//  >=
//这四种函数
           
// greater example
    #include <iostream>     // std::cout
    #include <functional>   // std::greater
    #include <algorithm>    // std::sort

    int main () {
      int numbers[]={,,,,};
      std::sort (numbers, numbers+, std::greater<int>());
      for (int i=; i<; i++)
        std::cout << numbers[i] << ' ';
      std::cout << '\n';
      return ;
    }
           

set集合默认排序方式 从小到大即less的,我们可以通过创建set的时候指定排序方式

set<int,greater<int>> m_set = { , , , , , , , ,  };
for each (auto var in m_set)
{
    cout << var << " ";
}
           

另外如果闲创建的比较繁琐我们可以用typedef来重命名

typedef std::set<int,std::greater<int>> IntSet;
typedef std::set<int,std::less<int>> IntSet;
IntSet my_set
IntSet::iterator ipos;