题目描述
有一群猫猫,每只猫都有自己的名称和体重。
用类来描述猫,名称和体重都是私有属性,要求加入属性的get方法。其他函数根据需要自己定义
创建一个动态的猫对象数组,存储各只猫的名称和体重
根据猫的体重对数组做升序排序,并输出排序后每只猫的名称
题目涉及的数值均用整数处理
输入
第一行输入n表示有n只猫
第二行输入一只猫的名称和体重
依次输入n行
输出
输出一行,输出排序后的猫的名称
输入样例1
4
chocolate 1500
water 400
cheese 3000
vegetable 200
输出样例1
vegetable water chocolate cheese
方法一:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
class Cats
{
string name;
double weight;
public:
Cats(){};
void setname(string _name);
void setweight(double _weight);
string getname();
double getweight();
};
void Cats::setname(string _name)
{
name=_name;
}
void Cats::setweight(double _weight)
{
weight=_weight;
}
string Cats::getname()
{
return name;
}
double Cats::getweight()
{
return weight;
}
bool compare(Cats c1,Cats c2)
{
if(c1.getweight()<c2.getweight())
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int T,i;
string _name;
double _weight;
i=0;
cin>>T;
Cats *c=new Cats[T];
for(i=0;i<T;i++)
{
cin>>_name;
cin>>_weight;
c[i].setname(_name);
c[i].setweight(_weight);
}
sort(c,c+T,compare);
for(int i=0;i<T-1;i++)
{
cout<<c[i].getname()<<" ";
}
cout<<c[T-1].getname()<<endl;
return 0;
}
方法二:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class cats
{
string name;
double weight;
public:
cats(){};
void setname(string _name);
void setweight(double _weight);
string getname();
double getweight();
};
void cats::setname(string _name)
{
name=_name;
}
void cats::setweight(double _weight)
{
weight=_weight;
}
string cats::getname()
{
return name;
}
double cats::getweight()
{
return weight;
}
bool compare( cats &c1, cats &c2)
{
if(c1.getweight()<c2.getweight())
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int T,i;
i=0;
cin>>T;
cats *c=new cats[T];
string _name;
double _weight;
for(i=0;i<T;i++)
{
cin>>_name;
cin>>_weight;
c[i].setname(_name);
c[i].setweight(_weight);
}
sort(c,c+T,compare);
for(i=0;i<T;i++)
{
cout<<c[i].getname();
if(i!=T-1)
{
cout<<" ";
}
else
{
cout<<endl;
}
}
}