C++最胖的加菲(类与对象+数组)

15 篇文章 1 订阅

题目描述

有一群猫猫,每只猫都有自己的名称和体重。

用类来描述猫,名称和体重都是私有属性,要求加入属性的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;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值