您的位置:首页 > 其它

以 公有成员为准 对class进行排序

2013-04-09 22:25 351 查看
int  必须为  public  (目前我只是自己研究透这个)

排序准则可以重载   默认升序   重载例如:
bool compare(const student &x, const student &y)      //降序排列   compar 可以换任意名字
{
return   x.score > y.score;
}
整体代码为:

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class student
{

public:
string name;
int score;
student(string str ,int score1)
{
name=str;
score=score1;
}
string getname()
{
return name;
}
void disp()
{
cout<<"name:      "<<name<<"            score:"<<score<<endl;
}

};
bool compare(const student &x, const student &y)      //降序排列
{
return   x.score > y.score;
}

int main()
{
student st[]={student("王华",78),student("shilei",100),student("范兄",99),student("小屁孩",56)};

vector <student> vec;
for(int i=0;i<4;++i)
vec.push_back(st[i]);

sort(vec.begin(),vec.end(),compare);     //compare  为排序基准    名字随意
cout<<"排序输出结果为:"<<endl;

for(vector<student>::iterator it=vec.begin();it!=vec.end();it++)
it->disp();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: