set集合容器的妙用(用于去重,排序)

set中自定义比较函数
使用insert()将元素插入到集合中去的时候,集合会根据设定的比较函数将该元素放到该放的节点上去。在定义集合的时候,如果没有

指定比较函数,那么采用默认的比较函数(按键值又小到大的顺序插入元素)。

编写比较函数的两张方法:

1.如果元素不是结构体,那么可以编写比较函数。

#include <iostream>  
#include <set>  
#include <iterator>  
using namespace std;  

//自定义比较函数myComp,重载操作符 ()  
struct myComp  
{  
    bool operator() (const int &a, const int &b)  
    {  
        return a > b;    //从大到小排序  
        //return a < b;  //从小到大排序  
    }  
};  

int main()  
{  
    set<int, myComp> s1;  
    for(int i = 1; i < 6; i++)  
        s1.insert(i*i);  
    s1.insert(8);  
    //ostream_iterator<int> output(cout, " ");  
    set<int, myComp>::iterator it = s1.begin();  
    for(; it != s1.end(); it++)  
    {  
        cout<<*it<<" ";  
    }  

    return 0;  
}  

2.如果元素是结构体,那么可以直接把比较函数写在结构体内。

#include <iostream>  
#include <set>  
#include <iterator>  
#include <string>  
using namespace std;  

struct Info  
{  
    string name;  
    float score;  
    //重载操作符<,自定义排序规则  
    bool operator< (const Info &a)const  
    {  
        //return a.score < score;    //按score由大到小排列  
        return a.score > score;  //由小到大排列  
    }  
};  

int main()  
{  
    set<Info> s;  
    Info info;  
    info.name = "Messi";  
    info.score = 8.5;  
    s.insert(info);  
    info.name = "Ronae";  
    info.score = 9.0;  
    s.insert(info);  
    info.name = "My";  
    info.score = 7.0;  
    s.insert(info);  
    info.name = "Perno";  
    info.score = 8.0;  
    s.insert(info);  
    info.name = "Arzar";  
    info.score = 8.5;  
    s.insert(info);  
    set<Info>::iterator it;  
    for(it = s.begin(); it != s.end(); it++)  
    {  
        cout<<it->name<<" : ";  
        cout<<(*it).score<<endl;  
    }  
        return 0;  
}  
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值