STL 中的 set 使用自定义比较运算符

来源:互联网 发布:ipadcad cad绘图软件 编辑:程序博客网 时间:2024/06/06 00:26

set 容器模版需要3个泛型参数,如下:

template<class T, class C, class A> class set;

第一个T 是元素类型,必选;
第二个C 指定元素比较方式,缺省为 Less<T>, 即使用 < 符号比较;
第三个A 指定空间分配对象,一般使用默认类型。

因此:
(1) 如果第2个泛型参数你使用默认值的话,你的自定义元素类型需要重载 < 运算操作;
(2) 如果你第2个泛型参数不使用默认值的话,则比较对象必须具有 () 操作,即:

bool operator()(const T &a, const T &b)

使用函数对象来自定义比较运算符:

#include <set>  #include <iostream>  using namespace std;  //首先实例化comp aa; 然后aa(lhs, rhs)进行比较  struct comp  {      bool operator ()(const int &a, const int &b)      {          return a>b;      }  };  int main()  {      set<int,comp> s;      s.insert(5);      s.insert(9);      s.insert(6);      s.insert(13);      s.insert(1);      set<int,comp>::iterator it;      for(it = s.begin(); it != s.end(); it++)          cout<<*it<<" ";      cout<<endl;      return 0;  }  

输出:

13 9 6 5 1

使用重载运算符自定义比较函数

#include <iostream>#include <set>using namespace std;struct comp{    int id;    bool operator <(const comp &a)const //排序并且去重复    {         return id>a.id;    }};set<comp> my; set<comp> ::iterator it; int main(){        for(int i=0;i<2;i++)        {           comp t1;           t1.id = i;            my.insert(t1);        }        for(it=my.begin();it!=my.end();it++)            cout<<(*it).id<<endl;    return 0;}
0 0