使用库函数实现自定义类型的排序

class Type
{
public:
	int a;
	Type(int x, int y):a(x),b(y){}
	Type():a(0),b(0){}
	int b;
};
使用qsort对自定义类型进行排序,需要提供一个比较函数,传递给qsort的函数指针参数
int compared(const void*x, const void *y)
{
	return ((Type*)x)->a - ((Type*)y)->a;
}
int main()
{
	int num = 12;
	srand(34);
	Type *tt = new Type[num];
	for (int i=0; i<num; ++i)
	{
		new(tt+i) Type(rand()%100, rand()%100);
	}
	qsort(tt, num, sizeof(Type), compared);
	for (int i=0; i<num; ++i)
	{
		cout<<tt[i].a<<" "<<tt[i].b<<endl;
	}
	return 0;
}
///set底层是红黑树,本可以排序,但是自定义类型的排序需要提供一个函数对象,实现比较大小功能

class compType
{
public:
	int operator()(Type x, Type y)
	{
		return x.a < y.a;
	}
};
int main()
{
	typedef set<Type, compType> settype;
	settype st;
	st.insert(Type(35, 2));
	st.insert(Type(32, 4));
	st.insert(Type(50, 5));
	settype::iterator it = st.begin();
	for ( ; it!=st.end(); ++it)
	{
		cout<<it->a<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值