有关 list中的sort(Comp compfunction )的问题

阿木zhang 2008-06-26 12:43:31
我定义了个Student类 然后压入list中,想要以Student中的age的大小进行排序,age是int型的
sort( Comp compfunction )里的Comp compfunction怎么写?
也就是比较规则该怎么写? 谢谢
ps:我可用分不多,就不给分了
...全文
215 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
baihacker 2008-06-26
  • 打赏
  • 举报
回复
less<int>()
richbirdandy 2008-06-26
  • 打赏
  • 举报
回复
1楼正解
hujinyong199 2008-06-26
  • 打赏
  • 举报
回复

#include "stdafx.h"
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;

struct student
{
int age;
char sex;
string number;
};

struct Cmp
{
bool operator()(const student stu1, const student stu2) const
{
return stu1.age < stu2.age;
}
};

void showMsg(const student *ptr)
{
cout<<ptr->age<<'\t'<<ptr->number<<'\t'<<ptr->sex<<endl;
}

int main()
{
list<student>lve;
student stu[3];
stu[0].age = 19;
stu[0].sex = 'm';
stu[0].number = "12435";

stu[1].age = 14;
stu[1].sex = 'm';
stu[1].number = "16465";

stu[2].age = 13;
stu[2].sex = 'f';
stu[2].number = "19545";

lve.push_back(stu[0]);
lve.push_back(stu[1]);
lve.push_back(stu[2]);

lve.sort(Cmp() );
typedef list<student>::const_iterator PTR;
for(PTR ptr = lve.begin(); ptr != lve.end(); ptr++)
{
showMsg( &(*ptr) );
}



return 0;
}





以上代码在VS2005中编译通过,在VC6.0下有一个错误,原因是VC6.0不支持
自定义的Cmp.
lyle3 2008-06-26
  • 打赏
  • 举报
回复


//不知道是不是这样的要求?
int comp(const void * p1, const void * p2)
{
return (*(int *)p1) - (*(int *)p2);
}

64,635

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧