结构体练习(第一阶段)

文章介绍了如何在C++中使用结构体数组存储银行卡记录,并通过`sort`函数实现按金额升序排序。作者给出了两种方法:一种是手动遍历找到最小值并交换位置,另一种是定义一个比较函数给`sort`使用。
摘要由CSDN通过智能技术生成

【问题描述】若有以下银行卡信息:
struct card{
    int id;//银行卡号
    int bonus; //金额
};
请编写程序,从键盘输入5条银行卡记录,使用结构体数组存
储这些数据,并按金额升序排序,输出排序后的结果。
【输入形式】5条银行卡记录分行输入,每行数据用空格间隔
【输出形式】分5行输出数据,每行数据均使用空格间隔
【输入样例】
1001  20
1002  80
1003  50
1004  10
1006  40
【输出样例】
1004  10
1001  20
1006  40
1003  50
1002  80
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/jshsjjn/article/details/125351925

#include<bits/stdc++.h>
using namespace std;
struct card{
    int id;
    int bonus;

}student[5];

int main()
{
    for(int i=1;i<=5;i++)
    {
        cin>>student[i].id>>student[i].bonus;
    }

    //进行排序的快速操作是啥来着?
    
    int m=0;
    int t=1;
    for(;m<5;)
    {
        
        int min=student[1].bonus;
        for(int i=1;i<=5;i++)
        {
            if(student[i].bonus<min)
            {
            min=student[i].bonus;
            t=i;
            }

        }
        cout<<student[t].id<<" "<<student[t].bonus<<endl;
        student[t].bonus=1000000;
        m++;
        t=1;


    }


}

用sort函数进行降序的方法

#include<bits/stdc++.h>
using namespace std;
struct card{
    int id;
    int bonus;

}student[5];

bool compare(card a,card b)
{
    return a.bonus<b.bonus;
}
int main()
{
     for(int i = 0; i < 5; i++) {
        cin >> student[i].id >> student[i].bonus;
    }

    sort(student,student+5,compare);

    for(int i = 0; i < 5; i++) {
        cout <<student[i].id <<" "<< student[i].bonus<<endl;
    }

    
}



原文链接:https://blog.csdn.net/jshsjjn/article/details/125351925

课后小结:

  • 也是比较轻松的
  • 记得有一种直接对结构体排序的方法,利用sort函数,需要定义一个bool函数
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值