轉載:https://blog.csdn.net/westbrook1998/article/details/81814305
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)
例子:
#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; }