C++的set重载运算符
转载: https://www.cnblogs.com/zhihaospace/p/12843802.html
set 容器模版需要3个泛型参数,如下:
template<class T, class C, class A> class set;
第一个T 是元素类型,必选;
第二个C 指定元素比较方式,缺省为 Less, 即使用 < 符号比较;
第三个A 指定空间分配对象,一般使用默认类型。
因此:
(1) 如果第2个泛型参数你使用默认值的话,你的自定义元素类型需要重载 < 运算操作;
(2)如果你第2个泛型参数不使用默认值的话,则比较对象必须具有 () 操作,即:
bool operator()(const T &a, const T &b)
例子:
//https://www.acwing.com/problem/content/submission/code_detail/8671714/
#include <bits/stdc++.h>
#define PII pair<int ,int>
using namespace std;
const int N = 2e5 + 10;
int a[N], b[N], p[N], c[N], ans[N];
int n, m;
struct cmp {
bool operator() (int a, int b) const {
return p[a] < p[b];
}
};
set<int,cmp> s[4];
bool st[N];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n ;
for(int i = 0; i < n; i ++ ) {
cin >> p[i];
}
for(int i = 0; i < n; i ++ ) {
cin >> a[i];
s[a[i]].insert(i);
}
for(int i = 0; i < n; i ++ ) {
cin >> b[i];
s[b[i]].insert(i);
}
cin >> m;
for(int i = 0; i < m; i ++ ) cin >> c[i];
for(int i = 0; i < m; i ++ ) {
int x = c[i];
bool flag = false;
while(1) {
if(s[x].empty()) break;
int res = *s[x].begin(); s[x].erase(res);
if(st[res]) continue;
else {
st[res] = true;
cout << p[res] << ' ';
flag = true;
break;
}
}
if(!flag) cout << "-1 ";
}
return 0;
}
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
int m,k;
struct cmp{
bool operator() (int a,int b){
if(abs(a-b)<=k){
return false;
}
else{
return a<b;
}
}
};
set<int,cmp> s;
char op[10];
int x;
int main(void){
scanf("%d%d",&m,&k);
while(m--){
scanf("%s%d",op,&x);
if(op[0]=='a'){
if(s.find(x)==s.end()){
s.insert(x);
}
}
else if(op[0]=='d'){
s.erase(x);
}
else{
if(s.find(x)!=s.end()){
puts("Yes");
}
else{
puts("No");
}
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现