sort函数的排序:
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <cmath>
#include <sstream>
#include <vector>
#include <queue>
using namespace std;
//自定义比较函数
bool cmp(const int& a,const int& b){//注意:本函数的参数的类型一定要与vector<elemType>中元素的类型一致
return a>b;
}
int main(){
int num[5]={1,12,5,66,43};
vector<int> a(num,num+5);
//默认排序从小到大
sort(a.begin(),a.end());
for(vector<int>::iterator it=a.begin();it!=a.end();++it)
cout<<*it<<" ";
cout<<endl;
//greater<int>() 从大到小
sort(a.begin(),a.end(),greater<int>());
for(vector<int>::iterator it=a.begin();it!=a.end();++it)
cout<<*it<<" ";
cout<<endl;
//自定义比较函数 从大到小
sort(a.begin(),a.end(),cmp);
for(vector<int>::iterator it=a.begin();it!=a.end();++it)
cout<<*it<<" ";
cout<<endl;
return 0;
}
简单地理解一下,greater<int>是int的比较函数,这个位置原本放的应该是“小于”的比较函数,但是这时我放了一个“大于”的比较函数上去,比较函数恰好反了过来,那么原来大根堆就变成小根堆了。
priority_queue:
1.普通方法
priority_queue<int> q;//通过操作,按照元素从大到小的顺序出队
priority_queue<int,vector<int>,greater<int> > q; //通过操作,按照元素从小到大的顺序出队
2.自定义优先级
struct cmp {
operator bool ()(int x, int y)
{
return x > y; // x小的优先级高 //也可以写成其他方式,如: return p[x] > p[y];表示p[i]小的优先级高
}
};
priority_queue<int, vector<int>, cmp>q; //定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
3.结构体声明方式
struct node {
int x, y;
friend bool operator < (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};
priority_queue<node>q; //定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//在重载”<”时,最好不要重载”>”,可能会发生编译错误
C++中定义比较函数的方法:
三种实现方式:
1. 定义 < 操作符。
使用这种方法可以使我们自定义的类能够获得与生俱来的排序能力。例如,如果有如下类:
第一种:
struct
Edge
{
int
from,to ,weight;
bool
operator <(Edge other)
const//const必须有
{
return
weight>other.weight;
}
};
第二种:
struct
Edge
{
int
from,to weight;
friend
bool
operator<(Edge a,Edge b)
{
return
a.weight>b.weight;
}
};
2. 自定义排序方法。
使用这种方式常常用在如下情形:
a.比较内置类型
b.不能修改需要比较的类型
c.除了类型自定义的比较方式以外的比较方法
简单来说,一个比较方法接收两个同类型的对象作为参数并且返回一个bool值,原型如下:
bool
name(T a,T b);
3. 重载()操作符
vector<int> occurrences; struct cmp { bool operator()(int a, int b) { return occurrences[a] < occurrences[b]; } };
set<
int
, cmp> s;
priority_queue<
int
, vector<
int
>, cmp> pq;
部分转自: