您的位置:首页 > 编程语言 > C语言/C++

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

2017-07-10 15:25 441 查看
http://www.cplusplus.com/reference/functional/less/

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

c++中的sort 排序函数

默认排序,从小到大

template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);


通过第三个参数来执行排序(从小到大或者从大到小)

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[] = {32,71,12,45,26,80,53,33};
std::vector<int> my_vector (myints, myints+8);
// 32 71 12 45 26 80 53 33

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

// using function as comp
std::sort (my_vector.begin()+4, 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 0;
}


my_vector contains: 12 26 32 33 45 53 71 80


另外,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[]={20,40,50,10,30};
std::sort (numbers, numbers+5, std::greater<int>());
for (int i=0; i<5; i++)
std::cout << numbers[i] << ' ';
std::cout << '\n';
return 0;
}


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

set<int,greater<int>> m_set = { 1, 1, 5, 3, 2, 9, 6, 7, 7 };
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: