Sets 执行期制定排序准则

 无论是将排序准则作为第二个template参数传入,或是采用缺省的排序准则less<>,通常你都会讲排序准则定义为型别的一部分。但是有时必须在执行期处理排序准则,或者你可能需要对同一种数据型别采用不同的排序准则。此时你就需要一个“用来表现排序准则”的特殊型别,使你能够在执行期间传递某个准则。以下范例程序说明了这种做法:

#include<iostream>
#include<set>
#include"print.h"
using namespace std;

//type for sorting criterion
template<class T>
class RuntimeCmp{
public:
enum cmp_mode{normal,reverse};
private:
cmp_mode mode;
public:
//constructor for sorting criterion default criterion uses value normal
RuntimeCmp(cmp_mode m = normal):mode(m){
}
//comparsion of elements
bool operator() (const T& t1,const T& t2)const{
return mode==normal ? t1<t2 : t2<t1;
}
//comparision of sorting criteria
bool operator == (const RuntimeCmp& rc){
return mode == rc.mode;
}
};
//type of a set that uses this sorting criterion
typedef set<int,RuntimeCmp<int> >IntSet;
//forward declaration
void fill(IntSet & set);


int main()
{

//creat,fill, and print set with normal element order uses default sorting criterion
IntSet coll1;
fill(coll1);
PRINT_ELEMENTS(coll1,"coll1: ");
//create sorting criterion with reverse element order
RuntimeCmp<int> reverse_order(RuntimeCmp<int>::reverse);
//create,fill,and print set with reverse element order
IntSet coll2(reverse_order);
fill(coll2);
PRINT_ELEMENTS(coll2,"coll2: ");
//assign elements AND sorting criterion
coll1 = coll2;
coll1.insert(3);
PRINT_ELEMENTS(coll1,"coll1: ");
//just to make sure
if(coll1.value_comp() == coll2.value_comp()){
cout<<"coll1 and coll2 have different sorting criterion "<<endl;
}
return 0;
}
void fill(IntSet& set)
{
//fill insert elements in random order
set.insert(4);
set.insert(7);
set.insert(5);
set.insert(1);
set.insert(6);
set.insert(2);
set.insert(5);
}


#include<iostream>
using namespace std;
/* PRINT_ELEMENTS()
* -prints optional C-string optcstr followed by
* -all elements of the collection coll
* -separated by spaces
*/
template<class T>
inline void PRINT_ELEMENTS (const T& coll,const char * optcstr=" ")
{
typename T::const_iterator pos;
cout<<optcstr;
for(pos = coll.begin();pos != coll.end(); ++pos)
cout<<*pos<<ends;
cout<<endl;
}

在这个程序中,RuntimeCmp<>是一个简单的template,提供“执行期间面对任意型别定义一个排序准则”的泛化能力。其default构造函数采用默认值normal,按升序排序;你也可以将RuntimeCmp<>::reverse传递给构造函数,便能按降序排序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值