急!关于排序的问题!

somebody_rj 2004-11-20 07:56:12
我定义了这样一个类
class Student
{
public:
Student();
Student(const string& name, const int age);
Student(const Student& rhs);
~Student();

void SetName(const string& name);
string GetName() const;
void SetAge(const int age);
int GetAge() const;

Student& operator=(const Student& rhs);

private:
string itsName;
int itsAge;
};

我想把这个student类的对象放进vector里!请问怎么样可以安itsAge从小到大排列?还有求出itsAge的平均值
...全文
163 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
somebody_rj 2004-11-21
  • 打赏
  • 举报
回复
再问一下!如果我重载了<和==操作附,那么sort函数应该怎么样写?是这样啊吗?sort(vs.begin(),vs.end())。
somebody_rj 2004-11-21
  • 打赏
  • 举报
回复
真是谢谢楼上几位了!
WuYL7812 2004-11-21
  • 打赏
  • 举报
回复
应该是multiset,用set不允许相同数据,但是年龄在这里显然是可以一样的。
y8t47h 2004-11-21
  • 打赏
  • 举报
回复
也可以使用 set 容器,这样就不用专门调用sort,当然仍然需要定义排序规则
WuYL7812 2004-11-21
  • 打赏
  • 举报
回复
是的,我自己是拿整数来练习使用这个函数的,就是这样调用
你可以试一试, 看结果
WuYL7812 2004-11-20
  • 打赏
  • 举报
回复
chinadragonss(独孤俊) 说得对
也可以这样
class CompareStud
{
public:
bool operator () (const Student &x, const Student &y)
{
if (y.itsAge > x.itsAge)
return true;
else
return false;
}
};
sort(vs.begin(),vs.end(),CompareStud());




bool func(const Student &x, const Student &y)
{
if (y.itsAge > x.itsAge)
return true;
else
return false;

}
chinadragonss 2004-11-20
  • 打赏
  • 举报
回复
一个简单例子,看了该知道怎么做了吧。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>



using namespace std;

class Student
{
public:
Student(){};
Student(int age)
{

itsAge = age;
};
// void SetName(const string& name);
// string GetName() const;
// void SetAge(const int age);
// int GetAge() const;

// Student& operator=(const Student& rhs);

//private:

int itsAge;
};

bool func(Student x,Student y)
{
if (y.itsAge > x.itsAge)
return true;
else
return false;

}


main()
{
Student a(300);
Student b(50);
Student c(100);
vector<Student> vs;
vs.push_back(a);
vs.push_back(b);
vs.push_back(c);


sort(vs.begin(),vs.end(),func);

for(int i = 0; i < vs.size();i++)
{
Student p = vs[i];
cout << p.itsAge<<endl;
}
}
oyljerry 2004-11-20
  • 打赏
  • 举报
回复
http://search.csdn.net/Expert/topic/1952/1952090.xml?temp=.1096765
oyljerry 2004-11-20
  • 打赏
  • 举报
回复
写一个比较函数
放到sort中去
fanbest 2004-11-20
  • 打赏
  • 举报
回复
排序算法那么多,随便找一个就行了呗。

计算平均数就更简单了,把第一个数作为flag,遍历整个数组,将每个itsage与flag相减的结果存起来,然后除以总人数后再加上flag就可以了。
oyljerry 2004-11-20
  • 打赏
  • 举报
回复
好像要重载<,然后比较
somebody_rj 2004-11-20
  • 打赏
  • 举报
回复
WuYL7812(龙哥)能不能写一段示例代码啊?我可以易于理解
WuYL7812 2004-11-20
  • 打赏
  • 举报
回复
要用STL里面的sort函数,要包含
#include <algorithm>

用#include <numeric>里面的accumulate函数可以求出总数(要自己写加的函数,传入这个函数)
除于总数就是平均值了
WuYL7812 2004-11-20
  • 打赏
  • 举报
回复
用STL里面的sort函数,你可以把你写的比较函数当作参数传到sort函数里,也可以重载比较大小运算符。
somebody_rj 2004-11-20
  • 打赏
  • 举报
回复
顶!大家来帮帮忙

64,644

社区成员

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

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