0%

Compare函数/类的使用

题目大意

这篇笔记对应的是「set 自定义 cmp 排序」:讲的是在 C++ 里如何为 set(以及类似容器)自定义比较器 cmp,从而改变元素的排序规则(例如从大到小排序),以及与默认比较方式的区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <set>
#include <iterator>
using namespace std;
int p[7]={0,4,3,2,1};
struct cmp{
bool operator()(int a,int b){
if(a!=b) return p[a]<p[b];
}
};
set<int,cmp > g; // 一般来说像set,priority_queue都是传入cmp,less<int> 这样的结构体
int main(){
g.insert(1);g.insert(2);g.insert(3);g.insert(4);
for(set<int>::iterator it=g.begin();it!=g.end();it++)
cout<<*it<<endl;
set<int>::iterator it=g.end();
advance(it,-1);
cout<<"back: "<<*it<<endl;
g.clear();
cout<<g.empty()<<endl;
}
1
2
3
4
5
6
4
3
2
1
back: 1
1

** 优先队列的比较符号是反的,解释详情见**

https://www.nowcoder.com/discuss/353157988535967744

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <queue>
using namespace std;
struct cmp {
bool operator() (pair<int, int> a, pair<int, int> b) {
// 如果第二个元素不同,则按照第二个元素比较
if (a.second != b.second)
return a.second > b.second; // 如果想要最小堆,这里使用 >
}
};
int a[]={1,2,4,1,492,412,3};

1
2
3
4
5
6
1 1
1 2
1 3
2 6
3 9
1 1 2 3 4 412 492