码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-15 21:30:59      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:


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;
}

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

标签:

原文地址:http://blog.csdn.net/yapian8/article/details/45064485

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!