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;
}使用库函数实现自定义类型的排序
最新推荐文章于 2023-03-02 11:36:40 发布
本文介绍了两种自定义类型的排序方式:一是使用C++标准库函数qsort配合比较函数实现;二是利用set容器并自定义比较函数对象进行排序。这两种方法为用户自定义的数据类型提供了灵活的排序解决方案。
742

被折叠的 条评论
为什么被折叠?



