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();
}
以 公有成员为准 对class进行排序
最新推荐文章于 2019-03-13 18:12:32 发布