c++几种重载
operator < 作为成员函数时得声明为const函数,表示不能修改对象的成员变量,保证被比较的两个对象内容不被修改。
operator< 作为独立函数声明时需要将两个对象都声明为const类型。
sort自带
sort(g,g+n,greater<int>()) // 注意有对括号
#include<iostream>
#include<algorithm>
//#include<functional> 标准库 不加也能用
using namespace std;
int main()
{
int a[10];
for(int i=0;i<5;i++)
a[i]=i;
sort(a,a+5,greater<int>()); //注意后边有对括号
for(int i=0;i<5;i++)
cout<<a[i]<<" ";
return 0;
}
输出
4 3 2 1 0
sort、map、set等的结构体重载
在sort,map,set中,重载< 使其从小到大排序 (set 默认是小根堆) 顺序和我们习惯的是相同的
struct node {
int key;
bool operator < (const node a) const {
return key < a.key;//从小到大排序
}
};
单元素的优先队列
priority_queue<int> a; //默认升序 priority_queue<int,vector<int>,greater<int> > b; //降序
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> a; //默认大到小
priority_queue<int,vector<int>,greater<int> > b; //小到大
a.push(3); a.push(2); a.push(1); a.push(9);
b.push(3); b.push(2); b.push(1); b.push(9);
while(!a.empty())
{
cout<<a.top()<<" ";
a.pop();
}
cout<<endl;
while(!b.empty())
{
cout<<b.top()<<" ";
b.pop();
}
return 0;
}
输出
9 3 2 1
1 2 3 9
多元素的优先队列-结构体
在priority_queue中,优先队列默认是大顶堆, 所以 d<x.d 为真时 是从大到小排序的,顺序和我们习惯的是相反的
struct node {
int key;
bool operator < (const node a) const {
return key < a.key; //从大到小排序
}
};
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct node1 //最大值优先
{
int x,y;
bool operator < (const node1 &a) const
{
return x<a.x;
}
}t1;
struct node2 //最小值优先
{
int x,y;
bool operator < (const node2 &a) const
{
return x>a.x;
}
}t2;
int main()
{
priority_queue<node1> q1;
priority_queue<node2> q2;
for(int i=0;i<5;i++)
{
t1.x=i; t1.y=i+1;
t2.x=i; t2.y=i+1;
q1.push(t1);
q2.push(t2);
}
cout<<"node1"<<endl;
while(!q1.empty())
{
t1=q1.top();
cout<<t1.x<<" "<<t1.y<<endl;
q1.pop();
}
cout<<endl<<"node2"<<endl;
while(!q2.empty())
{
t2=q2.top();
cout<<t2.x<<" "<<t2.y<<endl;
q2.pop();
}
return 0;
}
输出
node1
4 5
3 4
2 3
1 2
0 1
node2
0 1
1 2
2 3
3 4
4 5
本文来自博客园,作者:斯文~,转载请注明原文链接:https://www.cnblogs.com/zhiweb/articles/15483305.html

浙公网安备 33010602011771号