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;
}
posted @ 2021-11-06 20:12  ccz9729  阅读(493)  评论(0编辑  收藏  举报