stl序列容器(map和set)的仿函数排序

问题:set是一个自动有序的集合容器,这是set的一个最实惠的性质,从小到大,只要你插入进去,就有序了。但是,如果你不想要这个顺序呢,是不是可以人为控制set容器
的元素顺序呢?答案是,可以的,因为stl也是程序员设计的。
首先看stl的模板构造函数
explicit set ( const Compare& comp = Compare(), const Allocator& = Allocator() );
template
set ( InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator() );
set ( const set& x );
我们完全可以重定义set的构造函数里的比较函数,完成对set的自排序功能。

举例:
 52 bool fncomp (int lhs, int rhs) {return lhs
 53 struct classcomp {
 54     bool operator() (const int& lhs, const int& rhs) const
 55     {return lhs>rhs;} // 控制set逆序
 56 };
 57
 58 void testset()
 59 {
 60 // 第一种使用方法
 61     bool(*fn_pt)(int,int) = fncomp;
 62     set sixth (fn_pt);
 63 // 第二中使用方法
 64     set s;                 // class as Compare
 65     s.insert(4);
 66     s.insert(5);
 67     set::iterator it;
 68     for(it=s.begin();it!=s.end();it++)
 69     {
 70         cout<<*it<<" ";
 71     }
 72     cout <<endl;
 73 };

 注意:如果set元素是一个结构体,你最好要设置你的仿函数,不然set一般默认是按第一个字段排序的,而我们的实际情况是想按序号i排序:
 37 struct ST_Message
 38 {
 39 public:
 40     ST_Message(int seq, int64_t time, string strfrom, string strto, string strinfo){
 41     this->seq=seq;this->time=time;this->strfrom=strfrom;this->strto=strto;this->strinfo=strinfo;}

 44     int seq;
 45     int64_t time;
 46     string strfrom;
 47     string strto;
 48     string strinfo;
 49
 50     bool operator <(const ST_Message& other) const // 注意是const函数
 51     {
 52         if (seq != other.seq) // dtime按升序排序
 53         {
 54             return (seq < other.seq);
 55         }
 56         else if(time < other.time)
 57         {
 58             return (time < other.time);
 59         }
 60         else if(strcmp(strfrom.c_str(), other.strfrom.c_str()) != 0)
 61         {
 62             return (strcmp(strfrom.c_str(), other.strfrom.c_str()) < 0);
 63         }
 64         else if(strcmp(strto.c_str(), other.strto.c_str()) != 0)
 65         {
 66             return (strcmp(strto.c_str(), other.strto.c_str()) < 0);
 67         }
 68         else
 69         {
 70             return (strcmp(strinfo.c_str(), other.strinfo.c_str()) < 0);
 71         }
 72     }
 73 };

stl中自动有序的容器map也和set有相同的应用,如果你想快速理解,那么把这篇文章中的set改成map就差不多了。
总之,有序的stl容器在工程中应用什么方便和广泛,但是当我们需要自己的排序的时候,可以用仿函数来设置它!

 

转载于:https://www.cnblogs.com/viviman/archive/2012/10/30/2775103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值